This article introduces three methods to read xml files: newDOMDocument (), regular expression parsing xml, and parser function to read xml data. these methods are feasible, but the first one is better than the last one. newDOMDo... this article introduces three methods to read xml files: new DOMDocument (), regular expression parsing xml, and parser function to read xml data. these methods are feasible, but the first one is better than the last one.
The new DOMDocument () instance code is as follows:
load('books.xml');$books = $doc->getElementsByTagName("book");foreach ($books as $book) { $authors = $book->getElementsByTagName("author"); $author = $authors->item(0)->nodeValue; $publishers = $book->getElementsByTagName("publisher"); $publisher = $publishers->item(0)->nodeValue; $titles = $book->getElementsByTagName("title"); $title = $titles->item(0)->nodeValue; echo "$title - $author - $publisher/n";}?>
The code for regular expression parsing is as follows:
(.*?)/
/s", $xml, $bookblocks);foreach ($bookblocks[1] as $block) { preg_match_all("//(.*?)/
/", $block, $author); preg_match_all("//(.*?)/
/", $block, $title); preg_match_all("//
(.*?)/
/", $block, $publisher); echo ($title[1][0] . " - " . $author[1][0] . " - " . $publisher[1][0] . "/n");}?>
The books. xml file is as follows:
Jack Herrington
PHP Hacks
O'Reilly
Jack Herrington
Podcasting Hacks
O'Reilly
The following is an example of using the parser function to read xml data. the code is as follows:
"; If ($ name) echo $ xml_data ."
";} Function endElement ($ parser_instance, $ element_name) // function for ending a tag event {global $ name, $ position; $ name = false; $ position = false;}?>
The xml file code is as follows:
Zhang San
Manager
Li Si
Assistant
Parser is a php built-in parser used to process xml. its work consists of three events: start tag, read data, and end tag.
That is to say, when processing xml, the function performs the corresponding action to convert xml data whenever the start tag, data, and end tag are encountered.
Tutorial link:
Reprint at will ~ However, please keep the tutorial address★