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

Rajesh Kumar Yadav - Jul 21 '21 - - Dev Community

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:

header("Content-Type: text/plain");echo "Hello World";
Enter fullscreen mode Exit fullscreen mode

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:

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);
Enter fullscreen mode Exit fullscreen mode

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:

// Error: We cannot send any output before the headersecho "Hello";// All headers must be sent before ANY PHP outputheader("Content-Type: text/plain");echo "World";
Enter fullscreen mode Exit fullscreen mode

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .