본문 바로가기
  • AI (Artificial Intelligence)
Programming/PHP

How to read a value from JSON using PHP?

by 로샤스 2017. 7. 27.

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.










Reference: http://developer-paradize.blogspot.co.nz/2013/06/how-to-read-value-from-json-using-php.html











댓글