Json in PHP

Our first program will demonstrate JSON encoding and decoding in PHP. Here’s the full source code:

<?php

// We'll use these two classes to demonstrate encoding and
// decoding of custom types below.
class Response1 {
    public $Page;
    public $Fruits;
}

// In PHP, all properties are exported by default.
// We can use attributes to customize the JSON key names.
class Response2 {
    #[JsonProperty(name: "page")]
    public $Page;

    #[JsonProperty(name: "fruits")]
    public $Fruits;
}

// First we'll look at encoding basic data types to
// JSON strings. Here are some examples for atomic values.
$bolB = json_encode(true);
echo $bolB . "\n";

$intB = json_encode(1);
echo $intB . "\n";

$fltB = json_encode(2.34);
echo $fltB . "\n";

$strB = json_encode("gopher");
echo $strB . "\n";

// And here are some for arrays and objects, which encode
// to JSON arrays and objects as you'd expect.
$slcD = ["apple", "peach", "pear"];
$slcB = json_encode($slcD);
echo $slcB . "\n";

$mapD = ["apple" => 5, "lettuce" => 7];
$mapB = json_encode($mapD);
echo $mapB . "\n";

// PHP can automatically encode your custom data types.
$res1D = new Response1();
$res1D->Page = 1;
$res1D->Fruits = ["apple", "peach", "pear"];
$res1B = json_encode($res1D);
echo $res1B . "\n";

// You can use attributes on class properties
// to customize the encoded JSON key names. Check the
// definition of `Response2` above to see an example
// of such attributes.
$res2D = new Response2();
$res2D->Page = 1;
$res2D->Fruits = ["apple", "peach", "pear"];
$res2B = json_encode($res2D);
echo $res2B . "\n";

// Now let's look at decoding JSON data into PHP
// values. Here's an example for a generic data structure.
$byt = '{"num":6.13,"strs":["a","b"]}';

// We need to provide a variable where the JSON
// package can put the decoded data. This
// stdClass will hold an object of arbitrary data types.
$dat = json_decode($byt);
print_r($dat);

// In order to use the values in the decoded object,
// we can access them directly. PHP will automatically
// convert them to the appropriate type.
$num = $dat->num;
echo $num . "\n";

// Accessing nested data is straightforward.
$strs = $dat->strs;
$str1 = $strs[0];
echo $str1 . "\n";

// We can also decode JSON into custom data types.
// This has the advantage of adding additional
// type-safety to our programs.
$str = '{"page": 1, "fruits": ["apple", "peach"]}';
$res = json_decode($str, false, 512, JSON_OBJECT_AS_ARRAY);
print_r($res);
echo $res['fruits'][0] . "\n";

// In the examples above we always used strings as
// intermediates between the data and JSON representation.
// We can also stream JSON encodings directly to output.
$d = ["apple" => 5, "lettuce" => 7];
echo json_encode($d) . "\n";

To run the program, save it as json_example.php and use php:

$ php json_example.php
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"Page":1,"Fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
stdClass Object
(
    [num] => 6.13
    [strs] => Array
        (
            [0] => a
            [1] => b
        )
)
6.13
a
Array
(
    [page] => 1
    [fruits] => Array
        (
            [0] => apple
            [1] => peach
        )
)
apple
{"apple":5,"lettuce":7}

We’ve covered the basics of JSON in PHP here, but check out the PHP JSON functions documentation for more details.