Creating and Parsing JSON data with PHP

Advertisement

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,

{"id":"1","name":"mike","country":"usa","office":["microsoft","oracle"]}

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"]} ';
$obj=json_decode($json_string);

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;

Popularity: 16% [?]

Tags: ,

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Related Posts

» Parsing the XML in easy way using PHP
» Web Services and PHP – SOAP vs XML-RPC vs REST
» How did I reduce CPU overhead problem caused by MySql?
» How to filter user submitted data easily in PHP?

26 Comments on “Creating and Parsing JSON data with PHP”

  • Binny V A wrote on 5 October, 2008, 2:48

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

  • shakeel shrestha wrote on 5 October, 2008, 7:46

    Roshan,

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

  • Roshan wrote on 5 October, 2008, 15:22

    @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 ..

  • Felix wrote on 6 October, 2008, 9:28

    Roshan
    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

  • Roshan wrote on 12 October, 2008, 6:39

    @Felix – I agree with you man…

  • Satya Prakash Karan wrote on 15 October, 2008, 14:08

    Good one!

    I have also written on JSON in javascript:
    JSON

  • Carlos @ VPSmedia wrote on 24 October, 2008, 22:15

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

  • Ronald wrote on 27 October, 2008, 12:18

    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

  • Carlos @ webbynode wrote on 27 October, 2008, 15:41

    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.

  • Roshan wrote on 27 October, 2008, 15:47

    @Ronald – thanks mate

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

  • Carlos @ webbynode wrote on 27 October, 2008, 15:53

    @Roshan – Thanks mate, I was a bit confused between the two ways ;)

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

    Thanks

  • Nishant Nayan wrote on 8 February, 2009, 14:28

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

  • sohbet wrote on 2 July, 2009, 13:21

    hi good thank you master

  • George Brown wrote on 27 July, 2009, 5:50

    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!
    http://www.jsonpro.com

  • sourav ray wrote on 23 November, 2009, 9:53

    @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.

  • Harry wrote on 4 February, 2010, 0:58

    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?

  • TG wrote on 5 February, 2010, 11:33

    A free JSON Viewer: http://jsonviewer.stack.hu

  • Stochastik wrote on 23 February, 2010, 11:07

    Creating and Parsing JSON data with PHP, oh yeahhhhhhh

  • Tim Barsness wrote on 5 May, 2010, 19:48

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

  • Joseph Buarao wrote on 11 May, 2010, 2:24

    I need your help guys.. this is my problem, I want to display this json data using php what should I do..
    $json_string=’{“Complex”:
    {“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":"",
    "Showtime":[{"id":"62","cinema_id":"10","start":"11:30:00","movie_id":"35",
    "Movie":{"title":"Iron Man 2","mtrcb_rating":"GP"}},
    {"id":"63","cinema_id":"10","start":"14:30:00","movie_id":"35",
    "Movie":{"title":"Iron Man 2","mtrcb_rating":"GP"}},
    {"id":"64","cinema_id":"10","start":"17:30:00","movie_id":"35",
    "Movie":{"title":"Iron Man 2","mtrcb_rating":"GP"}},
    {"id":"65","cinema_id":"10","start":"20:30:00","movie_id":"35",
    "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”:”",
    “Showtime”:[{"id":"67","cinema_id":"11","start":"12:00:00","movie_id":"35",
    "Movie":{"title":"Iron Man 2","mtrcb_rating":"GP"}},
    {"id":"68","cinema_id":"11","start":"15:00:00","movie_id":"35",
    "Movie":{"title":"Iron Man 2","mtrcb_rating":"GP"}},
    {"id":"69","cinema_id":"11","start":"18:00:00","movie_id":"35",
    "Movie":{"title":"Iron Man 2","mtrcb_rating":"GP"}},
    {"id":"70","cinema_id":"11","start":"21:00:00","movie_id":"35",
    "Movie":{"title":"Iron Man 2","mtrcb_rating":"GP"}}]}]}
    Pls.. email me for the solution.. Thanks..

  • Malay Mehta wrote on 16 September, 2010, 11:33

    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 abc.com 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

  • khumlo wrote on 23 June, 2011, 10:21

    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?

Trackbacks

  1. Daily Find #107 | TechToolBlog
  2. Castup » Daily Find #107
  3. Fabián Link » Creating and Parsing JSON data with PHP
  4. pligg.com

Write a Comment

 


Copyright © 2013 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.