• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
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.

Check Out These Related posts:

  1. Fetching data using PHP and PDO with bound placeholders
  2. Ordering by specific field values with MySQL
  3. Load JSON data with jQuery, PHP and MySQL
  4. Load JSON data with jQuery and PHP – Radio Buttons

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap