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 were 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:
$cars = array (
array("name" => "BMW", "type" => "535", "engine" => 3.0),
array("name" => "BMW", "type" => "320", "engine" => 2.0),
array("name" => "Audi", "type" => "A4", "engine" => 3.0),
array("name" => "Audi", "type" => "S3 Sedan", "engine" => 3.0),
array("name" => "Mercedes", "type" => "A220", "engine" => 1.8),
array("name" => "Mercedes", "type" => "C220", "engine" => 2.2)
);
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:
echo json_encode($cars);
The result returned will be:
[
{"name":"BMW","type":"535","engine":3},
{"name":"BMW","type":"320","engine":2},
{"name":"Audi","type":"A4","engine":3},
{"name":"Audi","type":"S3 Sedan","engine":3},
{"name":"Mercedes","type":"A220","engine":1.8},
{"name":"Mercedes","type":"C220","engine":2.2}
]
I have published this code to my web site, so if you want to test the result, please go to this link http://arian-celina.com/json.php.
The whole code will look like this:
<?php
$cars = array (
array("name" => "BMW", "type" => "535", "engine" => 3.0),
array("name" => "BMW", "type" => "320", "engine" => 2.0),
array("name" => "Audi", "type" => "A4", "engine" => 3.0),
array("name" => "Audi", "type" => "S3 Sedan", "engine" => 3.0),
array("name" => "Mercedes", "type" => "A220", "engine" => 1.8),
array("name" => "Mercedes", "type" => "C220", "engine" => 2.2)
);
echo json_encode($cars);
The post Outputting json data with php appeared first on arian-celina.com.