note 81267 deleted from class.xmlreader by thiago

From: Date: Wed, 12 Nov 2008 13:42:39 +0000
Subject: note 81267 deleted from class.xmlreader by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146433@lists.php.net to get a copy of this message
Note Submitter: Jonathan Hurtado ---- Matt, Your recursive function to convert a multi-level XML file into an unordered list is great, but it has a flaw. The HTML it generates is not valid. This is how your function currently writes the HTML markup. <ul> <li></li> <ul> <li></li> <ul> <li></li> </ul> </ul> </ul> However, valid HTML dictates that when you nest a list inside another list, you must close the list inside the list item. Here is valid HTML markup for a nested list: <ul> <li> <ul> <li></li> </ul> </li> <!-- nested list must be closed inside list item --> </ul> I have tweaked your recursive function so that it writes valid HTML when writing nested lists. left_nav.xml: <root> <item name="Contact Information" url="some_url" /> <item name="Directions" url="some_url" /> <item name="Map" url="some_url" /> <item name="Links of Interest"> <item name="Labs/Centers/ Institutes" url="some_url" /> <item name="Journals/Societies" url="some_url" /> <item name="Other"> <item name="Brain Imaging" url="some_url" /> <item name="ASL" url="some_url" /> <item name="Miscellaneous" url="some_url" /> </item> </item> <item name="Gallery" url="some_url" /> </root> <?php $xml = new XMLReader(); $xml->open("left_nav.xml"); parseXML($xml); function parseXML($node) { if (!$node->read()) return; //If this is the root node, then just continue down the tree. if ($node->nodeType==XMLReader::ELEMENT && $node->value == "root") parseXML($node); //If this is a text node then test for attributes. if ($node->nodeType==XMLReader::ELEMENT && $node->hasAttributes) { if ($node->getAttribute("url") != "") { print "<li>"; print "<a href=\"" . $node->getAttribute("url") . "\">" . $node->getAttribute("name") . "</a>"; if ($node->isEmptyElement) { print "</li>"; //only prints closing list tag if item does not have children } print "\n"; } else { print "<li>"; print $node->getAttribute("name"); if ($node->isEmptyElement) { print "</li>"; //only prints closing list tag if item does not have children } print "\n"; } } //If it is the beginning node then start the list. if ($node->nodeType==XMLReader::ELEMENT && !$node->isEmptyElement) print "<ul>\n"; //If it is the end node then close the list. if ($node->nodeType==XMLReader::END_ELEMENT) { print "</ul>\n"; if ($node->name == "item") { print "</li>\n"; } //prints closing list tag for item that has children } //Call the recursive method again. parseXML($node); } ?>

« previous php.notes (#146433) next »