- Instant help with your Php coding problems

Extract data from JSON in PHP

How to extract data from JSON in PHP?
$jsonString = <<<JSON
    "name": "John",
    "age": "32",
    "address": {
        "city": "London",
        "street": "Laxin street 32",
        "zip": "32567"

$user = json_decode($jsonString);

$name = $user->name;
$city = $user->address->city;

To extract data from a JSON string in PHP first convert it to a JSON object using the json_decode method. The json_decode() method takes a JSON encoded string and converts it into a PHP variable. 

$data = json_decode($jsonString);

null is returned if the JSON cannot be decoded or if the encoded data is deeper than the nesting limit.

By default, the json_decode method returns an stdClass object. You can get the result as an associative array if sets the second parameter to true:

$dataArray = json_decode($jsonString, true);

So accessing data in JSON object is as simple as:

$city = $user->address->city;


Share "How to extract data from JSON in PHP?"