We support #BlackLivesMatters !
If you support us then follow us by clicking here and following us!

How to print Non-HTML output from web server using php?

For all PHP related discussion, one of the most popular programming languages on the web.
Post Reply
admin
Site Admin
Posts: 44

How to print Non-HTML output from web server using php?

Post by admin » Sun Nov 03, 2019 5:13 pm

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:

Code: Select all

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:

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

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

Post Reply