How to parse XML in PHP

parse-xml-php

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

 version='1.0'?>
>
  >
        >IAMROHIT>
        >Dellhi>
        >0000000>
  >
    >
        >IAMROHIT>
        >Dellhi>
        >0000000>
  >
>

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.


    $companydb = simplexml_load_file('companydb.xml');
    foreach ($companydb as $company) {
        echo $title=$company->name." - ".$company->city." - ".$company->phone."
"
; } ?>

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

Leave a Reply

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

Top