tags:

views:

17

answers:

2

Hi all,

I am creating an address book xml feed from a MySQL database, everything is working fine, but I have a section tag which gets the first letter of the surname and pops it in that tag. I only want this to display if it has changed, but for some reason my brain isn't working this morning!

Current code:

<?php

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
echo "<data>";

do {

    $char = $row_fetch["surname_add"];
    $section = $char[0];

    //if(changed???){
        echo "<section><character>".$section."</character>";
    //}
    echo "<person>";
    echo "<name>".$row_fetch["firstname_add"]." ".$row_fetch["surname_add"]."</name>";
    echo "<title>".$row_fetch["title_add"]."</title>";
    echo "</person>";

    //if(){
        echo "</section>";
    //}


} while ($row_fetch = mysql_fetch_assoc($fetch));

echo "</data>";

?>

Any help on this welcome, don't know why I can't think of it!

+1  A: 

To be sure that your XML is valid it is better to build a DOM tree, here is an example from the PHP manual:

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?> 
Ilian Iliev
+1  A: 

And if you still want to generate XML manually, I suppose, something like this will work:

$section = "NoSectionStartedYet";
while ($row_fetch = mysql_fetch_assoc($fetch)) {

    $char = $row_fetch["surname_add"];
    if ($char[0] != $section)
    {
        if ($section != "NoSectionStartedYet")
        {
            echo "</section>";
        }
        $section = $char[0];
        echo "<section><character>".$section."</character>";
    }

    echo "<person>";
    echo "<name>".$row_fetch["firstname_add"]." ".$row_fetch["surname_add"]."</name>";
    echo "<title>".$row_fetch["title_add"]."</title>";
    echo "</person>";

}
echo "</section>";
Kel
Have in mind that in this case you have no guarantee that the output will be a valid XML. For example this may happen if you have malformed html in the database like $row_fetch["title_add"] = 'title<b>'
Ilian Iliev