How to parse XML in PHP – simpleXML

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.
parse-xml-php
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.
See tutorial: Read RSS feed of website (blog) using php


Here is sample xml file.
companydb.xml

<?xml version='1.0'?>
<companydb>
  <company>
        <name>IAMROHIT</name>
        <city>Dellhi</city>
        <phone>0000000</phone>
  </company>
    <company>
        <name>IAMROHIT</name>
        <city>Dellhi</city>
        <phone>0000000</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.

See one more example based on the same approach.
Blog Spot Feed Reader

If you like this post please don’t forget to subscribe my public notebook for more useful stuff

Posted in: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.