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
$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="
Harry
harry@example.com
Harry2
harry2@example.com
";
$xml_string="
//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);
$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, '
';
}
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '
';
}