Amit Dhamu

Writes Code

Encode & Decode JSON

To decode a JSON string into a PHP array you can use json_decode and json_encode respectively.

$json = '[{"song":{"title":"Paradise","artist":"Coldplay","album":"Mylo Xyloto"}}]';
$decoded = json_decode($json);

// $decoded will output
Array (
    [0] => Array(
            [song] => Array (
                    [title] => Paradise
                    [artist] => Coldplay
                    [album] => Mylo Xyloto
                )
        )
)


Similarly you could use json_encode to make a JSON string from an array.

$array = array();
$array[0]['song']['title'] = "Paradise";
$array[0]['song']['artist'] = "Coldplay";
$array[0]['song']['album'] = "Mylo Xyloto";

$json = json_encode($array);

// $json will output
[{"song":{"title":"Paradise","artist":"Coldplay","album":"Mylo Xyloto"}}]


json / json_decode / json_encode / php

← SimpleXML Random Colour →