Saturday 31 May 2014

[Solved] Encode PHP Object or Array to JSON



INTRODUCTION


Hi Everybody, 

As it is well known that the easiest way to share data with mobile device application, is through web services and the majority of web services provide data at in the form of JSON (Javascript Object Notation) at the end point. 
   
So today I am going to show that how to encode a PHP object or array into JSON object or array to create web services so it can easily communicate with mobile device application. 

This is very simple and easy to implement.There is an built in function in PHP 

json_encode();


which encodes array or object to JSON 


so here is my code in PHP 


<?php


$Name = "Syed Mudassir Shah";
$Age = 20;

echo json_encode(array("Name" => $Name, "Age" => $Age));


This will give output a JSON object having name and age property.


Output:

{

  • Name: "Syed Mudassir Shah",
  • Age: 20
}

Now if we have an array of objects then we will encode php array in json array as following





$var =  array("Name" => $Name, "Age" => $Age);

echo json_encode(array("ArrayName" => $var)); 


This will give output as JSON array however there is only one object present in var if their are more than one object it will show all data in form of JSON array.

Output:

 {
  • ArrayName: {
    • Name: "Syed Mudassir Shah",
    • Age: 20
    }
}
 
Now if more than one object in an PHP array

<?php 
$Name = "Syed Mudassir Shah";
$Age = 20;

$var =  array();$var[] = array("Name" => $Name, "Age" => $Age);$var[] = array("Name"=> "Arham", "Age" => 22); 
echo json_encode(array("ArrayName" => $var)); 
  
?>
Now one more object is added now we will see it is showing like array or list of objects 
Output:
{
  • ArrayName: [
    • {
      • Name: "Syed Mudassir Shah",
      • Age: 20
      },
    • {
      • Name: "Arham",
      • Age: 22
      }
    ]
}
Now you are done with learning PHP to JSON encoding. If you want to parse or decode it for your mobile application use any parser, decoder or deserializer  recommend for your mobile phone application and parse this valid JSON and use required data. 
Note: There is one more way to encode JSON that is manual way by writing script using echo but I wouldn't recommend you because many of the decoder or parser doesn't recognize that kind of enoded JSON so be aware of that. 

To download sample files Click Here.

Thanks

Regards
Mudassir,


No comments:

Post a Comment