Using JSON in PHP
JSON is a great option for transferring data between servers and to the client because it’s the standardised way of doing it.
This is what JSON looks like:
{
"key": "value",
"number": 12
}
So in PHP you could receive JSON as a string and use in-built functions to convert it to an array or an object – json_decode.
Or, you could take an existing array or object in PHP and convert it to JSON to send on somewhere else – json_encode.
Encoding into JSON
We can encode an array or an object into JSON using the json_encode in-built PHP function.
It takes the following parameters:
- A value – anything that isn’t a resource and usually an array or object.
- A flag – an optional parameter which sets some options for the JSON that is output like pretty print (enter a 0 to skip this if you need the third parameter).
- Depth – a number greater than zero describing how far down an array or object the functin should go from the top (i.e., 2 = two levels).
Here’s some sample code:
<?php
$anArray = array('dan' => 1, 'ben' => 2, 'tom' => 3);
echo json_encode($arr);
// Output: {"dan":1,"ben":2,"tom":3}
?>
Decoding from JSON
And here’s an example going the other way around.
<?php
$json = '{"dan":1,"ben":2,"tom":3}';
var_dump(json_decode($json));
/*
Output:
object(stdClass)#1 (3) {
["dan"] => int(1)
["ben"] => int(2)
["tom"] => int(3)
}
*/
var_dump(json_decode($json, true));
/*
Output:
array(3) {
["dan"] => int(1)
["ben"] => int(2)
["tom"] => int(3)
}
*/
?>
And that’s how you work with JSON in PHP.
