Reading and writing JSON in PHP

PHP is a popular server-side scripting environment easily integrated with the Apache and Microsoft IIS web servers. It has native support for simple JSON encoding and decoding.

How to do it...

PHP provides two functions, json_encode and json_decode, to encode and decode JSON respectively.

You can pass primitive types or user-defined classes to json_encode and it returns a string containing the JSON representing the object. For example:

$result = array(
"call" =>"KF6GPE",
"type" =>"l",
"time" =>"1399371514",
"lasttime" =>"1418597513",
"lat" =>37.17667,
"lng" =>-122.14650,
"result" =>"ok");
$json = json_encode($result);

This creates a string $json containing the JSON representation of our associative array.

The json_encode ...

Get JavaScript JSON Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.