Home » PHP6 August 2013

PHP: Read Write JSON

JSON stands for JavaScript Object Notation. It is a light-weight text-based open standard designed for human-readable data. It is language-independent, with parsers available for many languages.

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML. [via Wikipedia:JSON]

JSON.com has a very good JSON basics with examples.

In this article, I will be showing how to convert PHP array into JSON format and then convert JSON string into PHP type.

PHP function json_encode is used to convert PHP array to JSON string.
PHP function json_deocde is used to decode a JSON string and convert it into a PHP variable.

Working with Single Dimensional Array

Suppose we have a simple single dimensional array:-

We encode the $mobiles array into JSON format using json_encode function:-

When we print $jsonMobiles string, we get the following output:-

Now, we use json_decode function to decode the JSON string and change it to PHP array.

From above, we have $jsonMobiles as a JSON string.

The following code will decode the JSON string and change it to PHP array:-

COMPLETE CODE

Read & Write JSON data to a file

Saving JSON data into a file

Reading JSON data from a file

Working with Multi Dimensional Array

Encoding

Suppose, we have a multi dimensional PHP array. We convert the array into JSON format using json_encode function.

Decoding

We convert the JSON string back to PHP object with json_decode function. And then print the PHP object.

Hope it helps. Thanks.

PHP

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • Andrey Nazarchuk

    Thanks man!