PHP – Fun with JSON
Today we will talk a little about JSON.
When it comes to Webservices communication, JSON is pretty much becoming the format of choice (the Rock Star! if i may) for many services/users. This preference is due to many reasons, mainly that it is lighter than it’s step sister (or brother) XML.
Let’s take this simple JSON string for example :
{
“Address” : “123 Anywhere St.”,
“City” : “Springfield”,
“PostalCode” : 99999
}
PHP comes with its native JSON parser/decoder. All you would need to do is call
json_decode()
Lets go through a quick example:
$directions ='{
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
}';
$json_array = json_decode($directions,true);
The first parameter is your JSON formatted string and your second parameter is BOOL value to wether you would like the array to be associative or not.
…now back to business:
The output of the print statement above will show you something like this:
Array ( [Address] => 123 Anywhere St. [City] => Springfield [PostalCode] => 99999 )
If you did your homework and read our tutorial on associative arrays, you know that you can now simply print the “Address” field using:
print $json_array["Address"];
output : 123 Anywhere St.
That was a simple JSON example to give you a feel of how things flow. Here’s a more complex (not too complex) example:
{
“Name”: “John Doe”,
“PermissionToCall”: true,
“PhoneNumbers”: [
{
"Location": "Home",
"Number": "555-555-1234"
},
{
"Location": "Work",
"Number": "555-555-9999 Ext. 123"
}
]
}
In the example above, PhoneNumbers is actually an array of values and not a single value; as you see the values are included in “[ ]” (opening and closing square brackets). Do not panic. Here’s how you would reference the “Location” type and “Number” for the first entry in the “PhoneNumbers” array:
print $json_array["PhoneNumbers"][0]["Location"] . "<br>"; print $json_array["PhoneNumbers"][0]["Number"];
output:
Home
555-555-1234
Similarly, this code
print $json_array["PhoneNumbers"][1]["Location"] . "<br>"; print $json_array["PhoneNumbers"][1]["Number"];
will output:
Work
555-555-9999 Ext. 123
That’s it folks. Play around with it. Create more complex strings and test them. Become the next JSON master…
I recommend reading http://www.json.org/ and http://php.net/manual/en/function.json-decode.php





