Hi,
This is probably very simple. Attempting to output an <ol> from the following XML with PHP. I’m unable to echo the <li> start element or</ol> end element. What did I goof?
<?xml version="1.0"?>
<list>
<item>Apples</item>
<item>Oranges</item>
<item>Pears</item>
<item>Peaches</item>
<item>Mangos</item>
<item>Bread</item>
<item>Cookies</item>
<item>Olives</item>
<item>Cheese</item>
<item>Bacon</item>
</list>
<?php
//The XML file that you wish to be parsed.
$xmlFile = "xml_items.xml";
/* The character data Handler
* Depending on what the currentElement is,
* the handler assigns the value to the appropriate variable
*/
function characterData($parser, $data){
echo $data;
}
/* The start Element Handler
* This function tells the parser to place a <b>
* where it finds a start eleement.
* This is also where we get the attribute, if any.
*/
function startElement($parser, $data){
if(strcmp($data,"item")==0){
echo "<li>";
}else{
echo "<ol>";
}
}
/*Creating the xml parser*/
function endElement($parser,$data){
echo "</li>";
}
/*Register the handlers*/
$xml_parser=xml_parser_create();
xml_set_element_handler($xml_parser,"startElement","endElement");
xml_set_character_data_handler($xml_parser,"characterData");
/*Open the xml file and feed it to the parser in 4k blocks*/
if(!($fp=fopen($xmlFile,"r"))){
die("Cannot Open $xmlSource ");
}
while(($data=fread($fp,4096))){
if(!xml_parse($xml_parser,$data,feof($fp))){
die(sprintf("XML error at line %d column %d ",
xml_get_current_line_number($xml_parser),
xml_get_current_column_number($xml_parser)));
}
}
//Free the memory used to create the parser.
xml_parser_free($xml_parser);
//Close the file when your done reading it.
fclose($fp);
?>
Source Code Ouput:
<ol>
<ol>Apples</li>
<ol>Oranges</li>
<ol>Pears</li>
<ol>Peaches</li>
<ol>Mangos</li>
<ol>Bread</li>
<ol>Cookies</li>
<ol>Olives</li>
<ol>Cheese</li>
<ol>Bacon</li>
</li>