How can the header 'Content-Type: application/json' impact the output of json_encode in PHP?
Setting the header 'Content-Type: application/json' informs the client that the response being sent is in JSON format. This can impact the output of json_encode in PHP by ensuring that the client interprets the response correctly. Without setting this header, the client may not recognize the response as JSON and may encounter parsing errors.
<?php
// Set the header to inform the client that the response is in JSON format
header('Content-Type: application/json');
// Encode data into JSON format
$data = array('key1' => 'value1', 'key2' => 'value2');
echo json_encode($data);
?>
Keywords
Related Questions
- How can the use of \r\n in PHP help address the problem of formatting text with double line breaks?
- How can PHP be used to dynamically generate links for navigating through content based on specific criteria?
- How can the Autocomplete plugin in PHP be customized to include additional data like the Personal Number?