Showing posts with label xml parsing. Show all posts
Showing posts with label xml parsing. Show all posts

Tuesday, March 1, 2011

Parse XML with PHP

Hi,

Parsing XML have been a headache for quit a few programmers, including me ;) . So in this post I will give a very simple approach to achieve it. First let us consider an XML file, "simple.xml" with the following content:


<products>
 <product>
  <name>iPhone</name>
  <currency>$</currency>
  <price>199.99</price>
 </product>
 <product>
  <name>Galaxy Tab</name>
  <currency>$</currency>
  <price>299.99</price>
 </product>
</products>

Our motive is to navigate through each product and display their details in a listed format such as:



During such parsing all you have to do is to use getElementsByTagName() function smartly. Here there is only 1 "products" tab but multiple "product" tag. So we need to run the loop on the "product" tag.

Here is how I have had done this. Create another file, "example.php" with the following: