Outputting json data with php

This is going to be a very short post, but could be of use if you did not know about this

Many times, for the purpose of demonstration when I teach AJAX requests to my students, I see the need to have a sample json dataset for easy consuming through AJAX requests. So basically what I want is to output an array of some JSON objects so we can consume let’s say using jquery and display them. I have found some examples, but strangely, none of them was appropriate for using in examples (they either had too much data that confused students, or had a complicated structure).

Usually, what first comes to our minds is that we need a Web Service for outputting json data with php, or perhaps even a REST service. No, for such an easy thing, we do not need a web service, we can achieve this with one line of code, yes, one line.

Let us create an array of arrays, where each array will hold the data of some famous cars:

If we have such an array of arrays, this could easily be translated to a JSON array with JSON objects inside it. The one line of code that we need to do this transformation is:

The result returned will be:

I have published this code to my web site, so if you want to test the result, please go to this link //arian-celina.com/json.php

The whole code will look like this:

 

If you enjoyed the article, please share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditEmail this to someone

Leave A Comment

Your email address will not be published. Required fields are marked *