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:
If the array was called $data, to convert and echo to the browser as JSON do this:
The resulting JSON encoded string would look like so:
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.
0 comments:
Post a Comment