PHP-XML Demo: List XML structure
This is a slightly modified example from the XML manual (The original
doesn't generate an html page and end elements are not shown).
Ok, here are the start and end elements found in the data file:
error_reporting(E_ALL);
$depth = 0;
$file = "story.xml";
// called when a the beginning of an element is found
function startElement($parser, $name, $attrs)
{
global $depth;
// this will do some nice indendation (3 spaces for each level)
for ($i = 0; $i < $depth; $i++) {
print " ";
}
print "$name\n
";
$depth++;
}
function endElement($parser, $name)
{
global $depth;
$depth--;
for ($i = 0; $i < $depth; $i++) {
print " ";
}
print "/$name\n
";
}
// parser creation
$xml_parser = xml_parser_create();
// definition of the event handler
xml_set_element_handler($xml_parser, "startElement", "endElement");
// open the file for reading, if it fails exit with a short message.
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}
// read the data and parse it, exit with a message when something goes wrong
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
// free the parser from memory
xml_parser_free($xml_parser);
?>
D.K.S.