Content-Type with header()
Learn to set the JSON response header with header('Content-Type: application/json').
The header function sets the response header
The header function sends an HTTP response header. The browser or client reads these headers to understand the content type and how to handle it. The most common header is Content-Type.
The header must be called before any output is sent. Otherwise the server raises a headers already sent warning. So header calls always come before output.
The application/ media type
For structured data format responses, the Content-Type header takes a media type starting with application/. This prefix marks the content as application data, so the client picks the correct parser.
The client reads the Content-Type header and interprets the body accordingly. When the header and body match, the API works cleanly; otherwise the client errors. So you always set the header before any output.
Exercise Set the header and print the data
Convert the array in $data to a structured data format string and print it. First set a Content-Type: application/... header with the header function (the format name is shown in the lesson title). Then encode the array and print it.
Show example solution
application/...'), then print with echo encode($data).
Example solution:
header('Content-Type: application/...');
echo encode($data);
Test yourself
-
What Content-Type for a structured data format response?
- A media type starting with application/
- text/html
- image/png
- text/plain
Show answer
A media type starting with application/ — Correct. Structured data format responses use a media type starting with application/.
-
Set the Content-Type header
$data = ['status' => 'ok']; ____('Content-Type: application/...'); echo encode($data);Show answer
$data = ['status' => 'ok']; header('Content-Type: application/...'); echo encode($data); -
Match the header concepts
- header()
- sends an HTTP header
- Content-Type
- declares the content type
- application/
- data format media prefix
- before output
- header call timing