This article describes the php parsing xml method in detail in the form of examples. Share it with everyone for your reference. The specific analysis is as follows:
The books.xml file is as follows:
?
2 3
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<🎜>//Create a DOMDocument object<🎜>
<🎜>$doc=new DOMDocument();<🎜>
<🎜>//Load XML file<🎜>
<🎜>$doc->load("books.xml");
//Get all book tags
$bookDom=$doc->getElementsByTagName("book");
foreach($bookDom as $book){
$title = $book->getElementsByTagName("title")->item(0)->nodeValue;
$author = $book->getElementsByTagName("author")->item(0)->nodeValue;
$year = $book->getElementsByTagName("year")->item(0)->nodeValue;
$price = $book->getElementsByTagName("price")->item(0)->nodeValue;
echo "title:".$title." "; echo "author:".$author." "; echo "year:".$year." "; echo "price:".$price ." "; echo "********************************** "; } ?> |
2. xml_parse_into_struct
Create a parser, parse xml data into an array, release the parser, and then extract the desired value from the array.
?
2 3
4 56 13 14 |
<🎜>//Read xml file<🎜>
<🎜>$file = "books.xml";<🎜>
<🎜>$data = file_get_contents($file);<🎜>
<🎜>//Create parser<🎜>
<🎜>$parser = xml_parser_create();<🎜>
<🎜>//Parse XML data into an array<🎜>
<🎜>xml_parse_into_struct($parser, $data, $vals, $index);<🎜>
<🎜>// Release the parser<🎜>
<🎜>xml_parser_free($parser);<🎜>
<🎜>//Array processing<🎜>
<🎜>$arr = array();<🎜>
<🎜>$t=0;<🎜>
<🎜>foreach($vals as $value) {<🎜>
<🎜>$type = $value['type'];<🎜>
<🎜>$tag = $value['tag'];<🎜>
<🎜>$level = $value['level'];<🎜>
<🎜>$attributes = isset($value['attributes'])?$value['attributes']:"";<🎜>
<🎜>$val = isset($value['value'])?$value['value']:"";<🎜>
<🎜>switch ($type) {<🎜>
<🎜>case 'open':<🎜>
<🎜>if ($attributes != "" || $val != "") {<🎜>
<🎜>$arr[$t]['tag'] = $tag;<🎜>
<🎜>$arr[$t]['attributes'] = $attributes;<🎜>
<🎜>$arr[$t]['level'] = $level;<🎜>
<🎜>$t ;<🎜>
<🎜>}<🎜>
<🎜>break;<🎜>
<🎜>case "complete":<🎜>
<🎜>if ($attributes != "" || $val != "") {<🎜>
<🎜>$arr[$t]['tag'] = $tag;<🎜>
<🎜>$arr[$t]['attributes'] = $attributes;<🎜>
<🎜>$arr[$t]['val'] = $val;<🎜>
<🎜>$arr[$t]['level'] = $level;<🎜>
<🎜>$t ;<🎜>
<🎜>}<🎜>
<🎜>break;<🎜>
<🎜>}<🎜>
<🎜>}<🎜>
<🎜>echo ""; print_r($arr); echo ""; ?> |
1 2 3 4 5 6 7 |
<🎜>$file="books.xml";<🎜>
<🎜>$xml = simplexml_load_file($file);<🎜>
<🎜>echo ""; print_r($xml); echo ""; ?> |