Showing posts with label PHP Built in Functions. Show all posts
Showing posts with label PHP Built in Functions. Show all posts

Thursday, 4 September 2014

What is the best way to return data in the JSON format from PHP?

If you are running PHP 5.2 or greater, you can use the built-in json_encode function to return JSON formatted data from PHP. Here is an example of it’s usage:

Example of returning JSON from PHP

$tennisArray = array('Djokovic' => 1, 'Federer' => 2, 
'Nadal' => 3, 'Murray' => 4);

echo json_encode($tennisArray);
The code above will output the JSON formatted data like this:
{"Djokovic":1,"Federer":2,"Nadal":3,"Murray":4}