How to Return JSON from a PHP Script

In this tutorial, we are going to show you the best and most effective way of returning JSON from a PHP script.

Below, you can see how to do it with the help of setting the Content-Type header.

Here is how you should use content- type header along with json_encode:

<?php

$data = ['foo' => 'bar'] /** whatever is being serialized **/; 
header('Content-Type: application/json'); 
echo json_encode($data);

?>

Describing JSON

JSON (JavaScript Object Notation) is considered a lightweight format applied to store and transport data.

It is commonly applied once data is forwarded from a server to a web page. JSON is quite simple to understand and use.

Syntactically, it is equivalent to the code used for generating JavaScript objects.