Decode JSON data with PHP

Add a comment August 7th, 2009

JSON, short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). If you are running your web server with latest PHP package, then it is so easy to decode JSON data with an in-built function of PHP. json_decode() function decodes a json string. It is available in PHP version 5.2 and later.

An Example:

<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
var_dump(json_decode($json)); 
var_dump(json_decode($json, true)); 
?>

Output of the above code will look like this:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Read more about JSON:

Share or Bookmark this Post:
  • StumbleUpon
  • Digg
  • Twitter
  • del.icio.us
  • Facebook
  • Mixx
  • MySpace
  • Reddit
  • Google Bookmarks
  • Yahoo! Buzz
  • Technorati
  • Live
  • DZone
  • Netvibes
  • RSS
  • Print

 

  1. August 8th, 2009 at 22:43 | #1
    Prashant

    Thanks Sachin, this helps me a lot in creating import script for MochiMedia.com game feed, because they provides data in JSON format and this function is the perfect for converting JSON data to an array and then running loop on that array, to use the data. :D

  2. August 8th, 2009 at 22:58 | #2

    I am glad that it helped you. It is one of the best feature of PHP, that you get almost everything with hundreds of internal (built-in) methods and ready to use. No further coding required. ;) :D

  3. August 9th, 2009 at 23:43 | #3

    Your posts are really very cool! Though I haven’t used JSON yet but at least learned about it :)

  1. No trackbacks yet.
Comments feed
Real Time Web Analytics