How to Write JSON Using PHP



PHP







In this article, we show how to write 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 write JSON data with PHP.

So below we show the code how to write (encode) JSON data with PHP.



So, first, in the code above we create an array which contains arrays. We assign this to the variable $books, since it is made up of arrays representing books. Within each of the arrays is the title property and the PublicationDate property. These hold the value of the title and the publication date of each book.

So the PHP equivalent of a JSON representation.

To actually encode this in JSON, we use the built-in PHP json_encode() function. This turns the PHP arrays within an array into JSON data, Javascript objects.

So it really is as simple as creating a PHP arrays within an overlapping parent array. This data can then be converted into JSON with the PHP built-in json_encode() function. So PHP makes it very easy to work with JSON with its built-in capabilities. Thus, PHP and JSON work very well with each, similarly how PHP works well with other technologies, seemingly flawlessly such as MySQL.

So taking the PHP code above, we get the following output shown below.

You can see how it's in beautiful JSON format.

Actual PHP Output


[{"title":"The Wandering Oz","PublicationDate":2007},{"title":"The Roaming Fox","PublicationDate":2009},{"title":"The Dominant Lion","PublicationDate":2012}]


Related Resources

How to Read JSON with PHP

HTML Comment Box is loading comments...