How to Return JSON from a PHP Script
This short tutorial will represent to you the most effective way of returning JSON from a PHP script.
In this tutorial, we will demonstrate the most effective way of returning JSON from a PHP script.
Below, you can see how to do it by setting the Content-Type header.
Here is how you should use the Content-Type header along with <kbd class="highlighted">json_encode</kbd>:
php content-type header, json_encode
<?php
$data = ['foo' => 'bar'] /** whatever is being serialized **/;
header('Content-Type: application/json');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
?>Note:
header()must be called before any output is sent to the browser.
Try it Yourself isn't available for this example.
Describing JSON
JSON (JavaScript Object Notation) is a lightweight format for storing and transporting data. It is commonly used to send data from a server to a web page. Syntactically, it is equivalent to JavaScript object notation.