Handling JSON with PHP - json_encode() and

PHP General Functions

JSON stands for JavaScript Object Notation. It is easily readable and writable by a wide range of scripting languages. It is a very simple, lightweight format, which can represent nested, structured data.

In PHP, you can use json_encode() function to turn either an array or an object into valid JSON. For example, the JSON that look like this:

{"message":"hello world"}

To generate it in PHP,

json_encode(array("message" => "hello world"));

To handle incoming JSON data and turn it into a structure you can use, simply use the json_decode() function, passing the string containing the JSON as the first argument. For example,

$data = json_decode('{"message":"hello world"}');

The output is an object.

When calling the json_decode(), it is possible to convert the data to an associative array rather than an object, by passing true as the optional second argument:

$data = json_decode('{"message":"hello world"}', true);

Whether you choose to work with objects or arrays is up to you, and really depends on the application and also the language.