How to parse a XML file using SimpleXML in PHP5?

SimpleXML is a very simple function introduced in PHP5 to parse a XML file. It is very simple to use and implement as compared to other bulky codes to parse a XML file. The steps are pretty simple. Let us use a simple XML file as below naming it as xmltest.xml.


<?xml version="1.0" encoding="UTF-8"?><Response>
 <statusCode>OK</statusCode>
 <statusMessage/>
 <ipAddress>173.200.52.93</ipAddress>
 <countryCode>US</countryCode>
 <countryName>UNITED STATES</countryName>
 <regionName>GEORGIA</regionName>
 <cityName>ATLANTA</cityName>
 <zipCode>30339</zipCode>
 <latitude>33.809</latitude>
 <longitude>-84.3548</longitude>
 <timeZone>-05:00</timeZone>
 </Response>

Now you can use the following php code to parse the above xmltest.xml file.

<?php
// load xml file
$xml = simplexml_load_file("xmltest.xml");
// print the name of the first element
echo $xml->getName() . "<br />";
// create a loop to print the element name and data for each node
foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  }
?> 


The above code will print the output as follows:

Response
statusCode: OK
statusMessage:
ipAddress: 173.200.52.93
countryCode: US
countryName: UNITED STATES
regionName: GEORGIA
cityName: ATLANTA
zipCode: 30339
latitude: 33.809
longitude: -84.3548
timeZone: -05:00

Comments

Popular posts from this blog

Getting latitude, longitude, timezone using ip address.