Monday, November 24, 2014

How to Read XML File in PHP With Using SimpleXML Language

As we all know that, the main purpose of XML is to allow sharing of data. Here, I am going to use Simple XML to read the Xml file.

Here, I am using my XML file name as blog.xml

For Example :-

 <articles>
    <article published="2012-03-04 13:10:26">
        <title>Online Education</title>
        <author>Hudson</author>
    </article>
    <article published="2013-07-14 16:27:42">
        <title>Popular Personality</title>
        <author>Emma</author>
    </article>
    <article published="2013-07-23 11:23:50">
        <title>Popular Movies</title>
        <author>Jhon</author>
    </article>
</articles>

Everything is case sensitive. So Small and capital letters, both are the different thing.

How to Read XML File in PHP Using SimpleXML

Read XML in PHP

To use simpleXML call simplexml_load_file() function , pass file name. It connects the XML file and converts into an object. So, you can access object properties using standard object notation.

If you are using older version of PHP then SimpleXML library will not work. It is only available in the PHP5 or higher version.

<?php

   // Read blog.xml file

   $xml = simplexml_load_file("blog.xml");

   // Print
   echo '<pre>'; print_r($xml);
?>

SimpleXMLElement Object
(
    [article] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [published] => 2012-03-04 13:10:26
                        )

                    [title] => Online Education
                    [author] => Hudson
                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [published] => 2013-07-14 16:27:42
                        )

                    [title] => Popular Personality
                    [author] => Emma
                )

            [2] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [published] => 2013-07-23 11:23:50
                        )

                    [title] => Popular Movies
                    [author] => Jhon
                )

        )
)

SimpleXML handle element attributes in this xml attribute is published.

Now we can process further the object in your PHP file, pick and format the contents as per the requirements.

 // Process XML

<?php

$xml = simplexml_load_file("blog.xml");

foreach ($xml as $xml_data){

        $title=$xml_data->title;  
        $author=$xml_data->author;
        $date=$xml_data['published']; // Attribute

        echo "<li> Post $title is written by $author on  $date</li>";
    }

?>a

0 comments:

Post a Comment