Home / Converting an array to JSON data with PHP

Converting an array to JSON data with PHP

PHP’s json_encode function converts a PHP variable into a JSON string which can then be used in Javascript, for example using jQuery’s JSON functions. This is easy to do and I’ll be combining the two together in tomorrow’s post to show how to fetch data from a MySQL database with PHP into Javascript via JSON.

Converting a PHP array to JSON

Assuming data had been selected from the database using my example fruit table into a multidimensional array with PDO::fetchAll using "SELECT * FROM fruit WHERE name = ‘Apple’", the array would look like so:

Array
(
    [0] => Array
        (
            [fruit_id] => 1
            [name] => Apple
            [variety] => Red Delicious
        )

    [1] => Array
        (
            [fruit_id] => 6
            [name] => Apple
            [variety] => Cox's Orange Pippin
        )

    [2] => Array
        (
            [fruit_id] => 7
            [name] => Apple
            [variety] => Granny Smith
        )

)

If the array was called $data, to convert and echo to the browser as JSON do this:

echo json_encode($data);

The resulting JSON encoded string would look like so:

[{"fruit_id":"1","name":"Apple","variety":"Red Delicious"},{"fruit_id":"6","name":"Apple","variety":"Cox's Orange Pippin"},{"fruit_id":"7","name":"Apple","variety":"Granny Smith"}]

Version requirements and further reading

PHP 5.2.0 or higher comes bundled with the JSON functions. Prior to 5.2.0 the PECL extension needs to be installed. Read the PHP JSON manual pages for more details.

There will be another post tomorrow which ties together three posts over the last few days and shows how to load JSON data with jQuery, PHP and MySQL.