How to Read JSON with PHP 


How to Read JSON with PHP


In this article, we show how to read JSON data with PHP.

JSON stands for JavaScript Object Notation. It began as a way to represent objects in Javascript, but along the way, many modern programming languages have built-in support for working with JSON. PHP is one of those languages that has built-in support for working with JSON, whether reading JSON data or writing JSON data.

JSON is a lightweight format; the size of the data packet is small and it is simple, which makes it fast and easy to process. This way, you can include web service content in your web page. You can also use AJAX requests to read JSON data asynchronously.

JSON is a good choice for mobile device applications; its small size and simple format allows for fast transfer of data, as well as placing minimal strain on the client device to decode it.

So we'll see in this article how to read JSON data with PHP.

So below we show the code how to read (decode) JSON data using PHP.

So, first, in the code above we create JSON data. We create book objects (objects that represent books). And for each book object, we specify what the title property is and what the publication data property is.

So this is data in JSON format.

We now want to read this JSON data using PHP.

To read JSON data, PHP has a built-in function, the json_decode() function, which converts JSON data into a PHP associative Each object in the array is converted into an element of the PHP associative array. The first book titled, "The Wandering Oz" is element 0. The second book is titled "The Roaming Fox" and it is element 1 in the array. The third book, titled "The Dominant Lion", is element 2.

We then use the print_r() function to show the contents of the PHP array.

We place the <pre></pre> tags in between the print_r() function just to make the result more readable.

The output of the PHP code above is shown below.

Actual PHP Output

    [0] => Array
            [title] => The Wandering Oz
            [PublicationDate] => 2007

    [1] => Array
            [title] => The Roaming Fox
            [PublicationDate] => 2009

    [2] => Array
            [title] => The Dominant Lion
            [PublicationDate] => 2012


Related Resources

How to Write JSON with PHP

HTML Comment Box is loading comments...