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 http://18.197.31.180/json.php

The whole code will look like this:

 

PHP Tutorial site

In many of my posts I have shown a positive attitude towards PHP programming language. Although it is not the language I use every day, I do consider PHP as one of the best programming languages for a beginner in web development because I believe it has a fairly easy learning curve. I am now announcing an initiative to create a small PHP tutorial site.

I have been teaching PHP for over four years, and it was always my language of preference when I had to explain web development concepts to someone. I have been teaching it in university level as well as a professional course, and I have seen that students have learned the most important parts of it very quickly.

As a supporting material to my courses, as well as to contribute globally in knowledge sharing, I am creating a new section in my site for PHP tutorials. You can see the page here. This section is going to be dedicated to several tutorials explaining basic concepts of PHP. This is going to be an evolving project of online teaching I am planning to implement during 2015, so I will be adding learning materials continuously. If you don’t want to miss anything, please subscribe, and you will receive them in your email.