In this beginner’s tutorial, I will show you how to print out JSON using PHP. I will also show you how to set the correct Content-Type header.
Let’s take a look at the following PHP script:
//Build our example data.
//In this case, it is an array.
$data = array(
'name' => 'John Doe',
'dob' => '1987-12-12',
'gender' => 'male',
'nationality' => 'Ireland'
//Convert our data into a JSON string.
$json = json_encode($data);
//Set the Content-Type header to application/json.
//Output the JSON string to the browser.
In the example above:
- We constructed our data. This is the data that we want to send back to the client in a JSON format. As you can see, it is a simple PHP array that contains information about a person called “John Doe”.
- We then converted our PHP array into a JSON string using the json_encode function. This function takes in a PHP value and return it’s JSON representation.
- After that, we used the header function to set the Content-Type to application/json. This is very important, as without it, certain clients will not be able to detect the fact that we are returning JSON data. It is always a good idea to tell the client what type of data you are returning.
- Finally, we printed out our JSON string.
If you load the PHP script in your browser, you will see the following output:
You can also check the “Content-Type” of your script by using your browser’s developer tools:
As you can see, our script is responding with a Content-Type of application/json.
To test your PHP script out, you can send an AJAX request to it and log the response to the browser console:
As you can see, the JSON data that we outputted with our PHP script is now available as a JSON object in the browser.
Hopefully, you found this short tutorial to be useful!