The header() function can send a raw HTTP header. You can add the Content-Type header to notify the browser of the content we are sending.
Consider the following code, where we set Content-Type as text/plain:
Code: Select all
header("Content-Type: text/plain");
echo "Hello World";
Hello World
To produce JSON content, use the application/json content type instead:
Code: Select all
header("Content-Type: application/json");
// Create a PHP data array.
$data = ["response" => "Hello World"];
// json_encode will convert it to a valid JSON string.
echo json_encode($data);
{"response":"Hello World"}
Note that the header() function must be called before PHP produces any output, or the web server will have
already sent headers for the response. So, consider the following code:
Code: Select all
// Error: We cannot send any output before the headers
echo "Hello";
// All headers must be sent before ANY PHP output
header("Content-Type: text/plain");
echo "World";
Warning: Cannot modify header information - headers already sent by (output started at
/dir/example.php:2) in /dir/example.php on line 3
When using header(), its output needs to be the first byte that's sent from the server. For this reason it's important to not have empty lines or spaces in the beginning of the file before the PHP opening tag <?php. For the same reason, it is considered best practice to omit the PHP closing tag ?> from files that contain only PHP and from blocks of PHP code at the very end of a file.