Creating and Parsing JSON data with PHP

Yesterday, I was in a party and a guy came near to me and asked me what is JSON and how can handle it via PHP. Today, I’m going to tell you something about JSON data and how we can handle them via PHP. Although, JSON stands JavaScript Object Notation, it is used by many other technologies like PHP and Java for data interchange format over the Internet.

What is JSON?

JSON is ultra-weight data interchange data format used over the internet for transferring the data. While XML is a dominant data interchange format over the internet but JSON is less complex and light-weight data.

Though it was first made to be used with JavaScript for accessing remote data, it is now used by many other languages because JSON data is platform independent data format.

Data Types and Example of JSON data

JSON supports various kind of data types which included numbers, strings, booleans as well as array datas and obviously object (collection of key:value pairs, comma-separated and enclosed in curly brackets).

Now, let’s look at the example of simple format of JSON data for a detail of a employee,


Creating and Parsing JSON data format in PHP

To handle JSON data there is JSON extension in PHP which is aviable after PHP 5.2.0. Two funcitons : json_encode() and json_decode() are very useful converting and parsing JSON data through PHP.

First of all, let’s look at the PHP code to create the JSON data format of above example using array of PHP.

$json_data = array ('id'=>1,'name'=>"mike",'country'=>'usa',"office"=>array("microsoft","oracle"));
echo json_encode($json_data);

The above code generates the JSON data exactly as above. Now, let’s decode above JSON data in PHP.

$json_string='{"id":1,"name":"mike","country":"usa","office":["microsoft","oracle"]} ';

Now, the $obj variable contains JSON data parsed in PHP object which you can display using code below.

echo $obj->name; //displays mike
echo $obj->office[0]; //displays microsoft

As you can guess,$obj->office is an array and you can loop through it using foreach loop of PHP,

foreach($obj->office as $val)
    echo $val;

26 thoughts on “Creating and Parsing JSON data with PHP

  1. If you are using PHP 4, let me recommend my array2json() function.

  2. Roshan,

    Can we use JSON as an alternative to XML in each cases. Or the two has their own special case of application.

  3. @Binny VA – cool function dude…..thanks for sharing this with us…

    @shakeel – as a data transfer format JSON can be used to alternative upto some extent but namespaces and other functionality makes XML stronger ..

  4. Felix

    In my view, both methods are usefull. JSON can be evaluated by through eval (fast, easy, you write a little aditional code), while XML requires an external source and is used for large volumes of data (you must write your function to examine the data). Both methods are equally effective, though JSON is more useful and easy for 80% of the procedures

  5. @Felix – I agree with you man…

  6. Good one!

    I have also written on JSON in javascript:

  7. Hey there, I thought JSON was mostly used to serialized connnections.

  8. simple and straight to the point, never really had time to read up on JSON but this is a very good intro to the subject

  9. Wouldn’t this be a good example too?

    JSON, is an object string notation. For people who are familiar with the serialize function available in the scripting languages, JSON wouldn’t be anything new. The reason for using JSON instead of the native php serialization is that JSON will work across languages. The advantage JSON provides over traditional XML or mere url notation output is that, with JSON all interactions happens via objects, and you don’t need to do any output parsing.

  10. @Ronald – thanks mate

    @Carlos @ webbynode – I would say that is very very good example…

  11. @Roshan – Thanks mate, I was a bit confused between the two ways 😉

    By the way, I’m sending you an email now.


  12. Nishant Nayan

    how can i print a variable “xmlns$gml” and “$t” in php, when these variables are returned within json data??

  13. hi good thank you master

  14. George Brown

    Sometimes when you have huge JSON documents its really difficult to read because they get all compressed and don’t have proper indentation. I found a really handy tool called JSON Pro Viewer that lets you work with JSON very easily!

  15. @Roshan nice article but the default php in json encoder / decoder cannot encode all characters, (hence omit them from the string). There are lots of libraries available to overcome this problem, most notable are PEAR JSON, XMLRPC JSON and Zend JSON Encoder.
    Personally I like Zend one, because it is a perfect trade off between character support and performance. If someone looking to support all utf8 charters go for XMLRPC library.

  16. Harry

    How do you take a json url, create the schema on the fly and push it into a db? Can you write a post on that?

  17. TG

    A free JSON Viewer:

  18. Stochastik

    Creating and Parsing JSON data with PHP, oh yeahhhhhhh

  19. You were at a party and someone asked you what JSON was? Sounds like quite the party…

  20. Joseph Buarao

    I need your help guys.. this is my problem, I want to display this json data using php what should I do..
    {“id”:”3″,”name”:”Cash and Carry”,”street_address”:”Corner Buendia and South Super Highway”,”city”:”Makati”,”phones”:”+63-2-856-5488″,”credit_card”:”0″},

    “Cinema”:[{“id”:”10″,”name”:”Cash and Carry Cinema 1″,”complex_id”:”3″,”theater_info”:””,”reserved_seating”:”0″,”reservation”:””,
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}},
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}},
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}},
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}}]},

    {“id”:”11″,”name”:”Cash and Carry Cinema 2″,”complex_id”:”3″,”theater_info”:””,”reserved_seating”:”0″,”reservation”:””,
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}},
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}},
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}},
    “Movie”:{“title”:”Iron Man 2″,”mtrcb_rating”:”GP”}}]}]}
    Pls.. email me for the solution.. Thanks..

  21. Malay Mehta

    Hi Roshan,
    Thanks for sharing and thanks to all other friends as well, but Roshan or anyone can suggest how to parse/fetch json objects from other site’s URL..

    Eg: If has 10 parameters, and I want to get the values for that parameters,… How do I do that??

    Thanks in advance.

    Many Thanks,
    Malay Mehta

  22. Nice blog… great content.

    Serialize data and JSON although they look similar, we cannot use alternately. Is there a way we can convert vice versa?

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>