Thursday, February 23, 2017

How to parse XML in PHP – simpleXML

Hello all,

Many websites on internet like to share their feed in XML format so that other website owner can show that feed on his/her website / blog. In PHP there is a function called simpleXML can simplify the process of reading the feeds into something useful for your web pages.

 If You have wordpress installed in your server you can also on Rss feed of your blog and share your news/ articles with other websites. this will increase your blog visibility and good for SEO also.

Here is sample xml file.
companydb.xml

<?xml version='1.0'?>
<companydb>
  <company>
        <name>Chirag</name>
        <city>Ahmedabad</city>
        <phone>121212</phone>
  </company>
    <company>
        <name>Parmar</name>
        <city>Mumbai</city>
        <phone>121212</phone>
  </company>
</companydb>
 With simpleXML, it’s as easy reading the XML file and then accessing it’s contents by an easy to read object. Suppose we have our XML file above saved as a file called comopanydb.xml with all the company details in the same folder as our php file, we can read the whole xml feed by following php function.

$companydb = simplexml_load_file('companydb.xml');
 
Now we have created file object, go next for accessing it’s content. 
like if you want to display the name of the all companies then use below
 code.
 
<?php
    $companydb = simplexml_load_file('companydb.xml');
    foreach ($companydb as $company) {
        echo $title=$company->name." - ".$company->city." - ".$company->phone."<br/>";
  } 
?>
 
Above is the quick example for parsing xaml data in php, you can store you 
data in xml file and access with this method.  
 

No comments:

Post a Comment