PHP Getting started with PHP Non-HTML output from web server

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

In some cases, when working with a web server, overriding the web server's default content type may be required. There may be cases where you need to send data as plain text, JSON, or XML, for example.

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:

header("Content-Type: text/plain");
echo "Hello World";

This will produce a plain text document with the following content:

Hello World

To produce JSON content, use the application/json content type instead:

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);

This will produce a document of type application/json with the following content:

{"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:

// 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";

This will produce a warning:

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 (see PSR-2) 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.

View the output buffering section to learn how to 'catch' your content into a variable to output later, for example, after outputting headers.



Got any PHP Question?