Converting an array to JSON data with PHPConverting an array to JSON data with PHP

Posted March 1st, 2010 in 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.

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus