Many new PHP developer looking for how to easily read the xml file. In this tutorial I will show you how to read the xml file using PHP language. Here I given the sample code for parsing the XML using PHP.

How to read xml using php

This is my xml file format and file name is readxml.xml file

<?xml version="1.0"?>

<!-- our XML-document describes a purchase order -->


 <name>My name</name>
 <address>My address</address>

 <!-- a collection element, contains a set of items -->

 <label>Some music</label>

 <label>Some video</label>



This is one php file called test.php and code as follows

 //create new document object
 $dom_object = new DOMDocument();
 //load xml file

 $item = $dom_object->getElementsByTagName("item");

 foreach( $item as $value )
 $codes = $value->getElementsByTagName("code");
 $code  = $codes->item(0)->nodeValue;

 $types = $value->getElementsByTagName("type");
 $type  = $types->item(0)->nodeValue;

 $labels = $value->getElementsByTagName("label");
 $label  = $labels->item(0)->nodeValue;

 echo "$code - $type - $label <br>";

When you run the readxml.php file. you will see the following output.

687 – CD – Some music
129851 – DVD – Some video

Written by Purab Kharat

I Purab am from India, Pune. I am WordPress and Drupal Architect and consultant. I worked on many technologies like Ruby on Rails, Flex, PHP, jQuery etc... Senior Technical Lead at Smartsourcing Global Pvt Ltd in Princeton, NJ, USA.I contributed to many wordpress plugins and Drupal Modules. I contributed to Drupal core also.Connect to purab on LinkedIn or Follow @purab on Twitter or Follow me on Google+ or Write Mail to or Chat with me on Skype : purabdk

This article has 2 comments

  1. Jonathan Reply

    How Can I get XML information from an specific URL with variables, I am working in my travel agency web page and my wholesaler provider give me the catalog in a xml url source and I am doing the web page in WordPress.. Can you help me?

  2. Mr D Reply

    Cannot thank you enough for this!!!
    This saved me an untold amount of time!
    You rock!

Leave a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>