PHP Parse XML Method Instance detailed

Source: Internet
Author: User
Tags foreach

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:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20-21 <?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 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

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?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.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The

3. Read XML-----XML simple API (sax) parser with SAX parser

?

1 2 3 4 5 6 7 <?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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.