Thursday , November 7 2024

Parse XML Data

Parsing XML essentially means navigating through an XML document and returning the relevant data. An increasing number of web services return data in JSON format, but a large number still return XML, so you need to master parsing XML if you really want to consume the full breadth of APIs available.

Using PHP’s SimpleXML extension that was introduced back in PHP 5.0, working with XML is very easy to do. In this article I’ll show you how.

//xml string  
$xml_string="<?xml version='1.0'?> 
<users> 
   <user id='398'> 
      <name>Foo</name> 
      <email>foo@bar.com</name> 
   </user> 
   <user id='867'> 
      <name>Foobar</name> 
      <email>foobar@foo.com</name> 
   </user> 
</users>";  
  
//load the xml string using simplexml  
$xml = simplexml_load_string($xml_string);  
  
//loop through the each node of user  
foreach ($xml->user as $user)  
{  
   //access attribute  
   echo $user['id'], '  ';  
   //subnodes are accessed by -> operator  
   echo $user->name, '  ';  
   echo $user->email, '<br />';  
}  

 

About admin

Check Also

Resize Images in php

Creating thumbnails of the images is required many a times, this code will be useful …

Leave a Reply