Tuesday, 1 January 2013

PHP JSON and XML Parser: How to Parse JSON and XML using PHP Script?

PHP JSON and XML Parser: How to Parse JSON and XML using PHP Script?

Parsing XML and JSON is very common application requirement as all the webservices provide data in the form of JSON and XML. PHP has very simple ways to parse XML and JSON. To parse JSON with PHP script, you have to use "json_decode" PHP function. We have given below the PHP JSON Parser code which is very simple. Similarly, using PHP script you can easily create PHP XML Parser. Using simplexml_load_string function, you can easily parse XML in PHP.

Below is the PHP code to parse JSON and XML:

PHP JSON Parser: How to Parse JSON using PHP Script?

$json_string='{"id":101,"name":"Harry","email":"harry@example.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints Harry
echo $obj->interest[1]; //prints php

PHP XML Parser: How to Parse XML using PHP Script?

//xml string
$xml_string="<?xml version='1.0'?>
<users>
   <user id='101'>
      <name>Harry</name>
      <email>harry@example.com</name>
   </user>
   <user id='102'>
      <name>Harry2</name>
      <email>harry2@example.com</name>
   </user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node
foreach ($xml->user as $user)
{
   //access attribute
   echo $user['id'], '  ';
   //subnodes are accessed by -> operator
   echo $user->name, '  ';
   echo $user->email, '<br />';
}

2 comments:

  1. Very simple to understand thanks for the information about xml parsing.

    ReplyDelete
  2. What about for non techies, can you suggest any tools for parsing xml like editix or liquid studio?

    ReplyDelete