0

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!

2 Answers 2

1

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>";
Sign up to request clarification or add additional context in comments.

1 Comment

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>'
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.