简体   繁体   中英

creating xml with php and 'if changed' option

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!

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();
?> 

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>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM