Guides retrieve data from parse XML to PHP

PHP

Posted on 2015-06-30 02:29:50


To the more you enjoy, I would imagine given a specific illustrative examples as follows. Here, I will not say the specific knowledge of XML if you do not clear, you can see the previous articles of yourselves.
First you create a file  test.xml  in directory  \ WAMP \ www . With content following code.
<?xml version="1.0" encoding="utf-8"?>
<library name="mylibrary">
    <book>
        <title>Begin PHP</title>
        <author>Tutscode tutorial</author>
        <category>Hello world</category>
    </book>
    <book>
        <title>sharing experiences with tutscode.com</title>
        <author>Tutscode tutorial</author>
        <category>Hello world</category>
    </book>
    <book>
        <title>Become developer with tutscode</title>
        <author>Tutscode tutorial</author>
        <category>Hello world</category>
    </book>
    <book>
        <title>PHP in tutscode</title>
        <author>Tutscode tutorial</author>
        <category>Hello world</category>
    </book>
</library>
To access the XML file we use PHP's SimpleXML extension. Next you create files testxml.php  in  \ wamp \ www  and then enter the code below into.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
     $xml = simplexml_load_file("books.xml") or die("Unable to load XML file."); //load file xml
     foreach($xml->book as $book){
         echo "Tiêu đề: ".$book->title." - Tác giả: ".$book->author." - Thể loại: ".$book->category."<br />";
     }
?>
After creating a connection to the xml file and assigned to the variable xml, we can access the data by pointing to the correct card data card with the position they appear in the xml file (eg $ XML- > Book-> title) or use the loop to retrieve all data. Eventually you run out to your browser and see the results offline. Good luck!