This article describes the PHP parsing XML method in detail in the form of an instance. Share to everyone for your reference. The specific analysis is as follows:
books.xml files are as follows:
<?xml version= "1.0" encoding= "iso-8859-1"?>
<bookstore>
<book category= "Children" >
<title lang= "en" >harry potter</title>
<author>j K. rowling</author>
<year> 2005</year>
<price>29.99</price>
</book>
<book category= "Cooking" >
<title lang= "en" >everyday italian</title>
<author>giada De laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category= "Web" cover= "Paperback" >
<title lang= "en" >learning xml</title>
<author> Erik T. ray</author>
<year>2003</year>
<price>39.95</price>
</ Book>
</bookstore>
1. DOM Parsing xml
<?php
//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. " <br> ";
echo "Author:". $author. " <br> ";
echo "Year:". $year. " <br> ";
echo "Price:". $price. " <br> ";
echo "***********************************<br>";
>
2, Xml_parse_into_struct
Create a parser, parse the XML data into an array, release the parser, and then extract the desired value from the array.
<?php/Read XML file $file =" books.xml ";
$data = file_get_contents ($file);
Create parser $parser = Xml_parser_create ();
Parsing XML data into an array of 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 "<pre>";
Print_r ($arr); echo "</pre>";?>
3. Read XML-----XML simple API (sax) parser with SAX parser
<?php
$file = "books.xml";
$xml = Simplexml_load_file ($file);
echo "<pre>";
Print_r ($xml);
echo "</pre>";
? >
I hope this article will help you with your PHP program design.