Here’s an example of a PHP header for sending data in JSON format:
PHP
<?php
// Set the content type header to application/json
header("Content-Type: application/json; charset=UTF-8");
// Your data to be encoded in JSON format
$data = array(
"message" => "Hello, world!",
"data" => array(
"name" => "John Doe",
"age" => 30
)
);
// Encode the data to JSON string
$json_data = json_encode($data);
// Echo the JSON data
echo $json_data;
?>
Explanation:
header
Function: Theheader
function is used to send HTTP headers to the browser. In this case, we’re setting theContent-Type
header toapplication/json
. This tells the browser that the following data is in JSON format.charset=UTF-8
: Specifyingcharset=UTF-8
ensures proper encoding of characters, especially if your data contains characters outside the basic ASCII range.- Data to Encode: The
$data
variable holds the information you want to send as JSON. It can be an array of key-value pairs, a single object, or any other data structure that can be encoded byjson_encode
. json_encode
Function: This function converts the PHP data structure ($data
) into a JSON string.echo
Statement: Finally, theecho
statement sends the JSON string ($json_data
) to the browser.
Running the Script:
Save this code as a PHP file (e.g., json_example.php
) and run it on your server. When you access the script in your browser, it should display the JSON data:
JSON
{"message":"Hello, world!","data":{"name":"John Doe","age":30}}
This demonstrates a basic example of sending JSON data from a PHP script. You can modify the data structure and logic according to your specific needs.