Nápověda:Parsování v PHP
Z VirtlabWiki
Oba skripty načítají XML soubor a pak se ho snaží zobrazit v HTML.
Poznámka: ukázka pro DOM, je realizovaná v PHP4 (v PHP5 je DOM implementován jinak).
[editovat]
DOM
<?php $file = "vybaveni.xml"; $indent = ""; $showfile = file_get_contents($file); // whatever path $newstring = utf8_encode($showfile); // it's important! if(!$domDocument = domxml_open_mem($newstring)) { echo "Couldn't load xml..."; exit; } $rootDomNode = $domDocument->document_element(); print "<pre>"; printElements($rootDomNode); print "</pre>"; function printElements($domNode) { if($domNode) { global $indent; if($domNode->node_type() == XML_ELEMENT_NODE) { print "<br />".$indent."<".$domNode->node_name(); if($domNode->has_attributes()) { $attributes = $domNode->attributes(); foreach($attributes as $domAttribute) { print " $domAttribute->name=\"$domAttribute->value\""; } } print ">"; if($domNode->has_child_nodes()) { $indent.=" "; $nextNode = $domNode->first_child(); printElements($nextNode); $indent= substr($indent, 0, strlen($indent)-2); print "<br />".$indent."<"."/".$domNode->node_name().">"; } } else if($domNode->node_type() == XML_TEXT_NODE) { echo(trim($domNode->node_value())); } $nextNode = $domNode->next_sibling(); printElements($nextNode); } } ?>
[editovat]
SAX
<?php function startElement($parser, $name, $attribs) { echo("<ul><li><$name><br/><ol>\n"); while(list($idex, $hodnota) = each($attribs)) { echo("<li>$idex = $hodnota</li>\n"); } echo("</ol>"); } function endElement($parser, $name) { echo("<li></$name></li>\n</ul>\n"); } function cdata($parser, $data) { $tmp=trim($data); if(!empty($tmp)) echo("data = \"$data\"<br/>\n"); } $parser = xml_parser_create("UTF-8"); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false); xml_set_element_handler($parser, "startElement", "endElement"); xml_set_character_data_handler($parser, "cdata"); $file="vybaveni.xml"; if(!($fp = fopen($file, "r"))) { die("Nelze otevrit soubor"); } while($data = fread($fp, 4096)) { if(!xml_parse($parser, $data, feof($fp))) { die(sprintf("Chyba %d %d", xml_get_current_line_number($parser), xml_get_current_column_number($parser))); } } ?>