Monday, June 17, 2013

How to read a value from JSON using PHP?

JSON (JavaScript Object Notation) is a convenient, readable and easy to use data exchange format that is both lightweight and human-readable(like XML, but without the bunch of markup).

If you have a json array and want to read and print its value, you have to use php function
json_decode(string $json, [optional{true, false}]).

If you pass a valid JSON string into the json decode function, you will get an object of type stdClass back. Here's a short example:
<?php
$string = '{"first_name": "Anup", "last_name": "Shakya"}';
$result = json_decode($string);

// Result: stdClass Object ( [first_name] => Anup: [last_name] => Shakya  )
print_r($result);

// Prints "Anup"
echo $result->first_name;

// Prints "Shakya"
echo $result->last_name;
?>

If you want to get an associative array back instead, set the second parameter to true:
<?php
$string = '{"first_name": "Anup", "last_name": "Shakya"}';
$result = json_decode($string, true);

// Result: Array ( [first_name] => Anup: [last_name] => Shakya  )
print_r($result);

// Prints "Anup"
echo $result['first_name'];

// Prints "Shakya"
echo $result['last_name'];
?>

If you want to know more about JSON, here is an official website of JSON.

2 comments:

  1. Its really good clarification. I used it. thanks. http://www.phptutorials.club

    ReplyDelete