Output Json Header In PHP

Overview of JSON

JSON http://www.json.org/ is an acronym for JavaScript Object Notation. It is essentially a way of exchanging data between a source and destination using name/value pairs. Commonly used when transferring data from a database to a website using AJAX.

Generating a JSON object using php is pretty simple (although it won’t be covered in this article), the lesser known technique is setting the correct content type so that the php page that generates the JSON object is seen as an actual JSON object rather than a plain text/html page.

Some libraries such as jQuery.getJSON() will detect wether or not the html page is a json response by looking at the Content-Type header of the response.

Json Content Type

What I mean by the correct content type is that each file type has its own content type which tell the browser how to handle the file. It informs the browser of what type of file follows so the browser is more aware on how to handle the content. For example a css file is seen as text/css where as an html or php file is seen as a text/html and likewise an image file can be image/jpg or image/png.

For a complete list of mime-types view this article or if you want to learn how to determine a mime-type of a file, click here.

Output Json Header In PHP

As for JSON, it can be output as a javascript file but also output as a json file. To overwrite the default content of text/html that the php file will most likely be, we will set the correct headers using php’s header(); function as you can see below.

Output as Json Using PHP Headers

<?php

// set our content-type to json
//  note that a Content-type of application/javascript works just as well as application/json
header('Content-Type: application/json');

// now output our json object
echo '{"name":"darian","lastname":"brown","age":87,"adress":{"21 somewhere street","my city","Australia"}}';

?>

Now when the page is loaded, the page will be seen as a JSON script rather than a simple html page.

Convert PHP Array to JSON Object

It is very easy to convert a php array into a json object using the php function json_encode(). It simply takes a multidimensional php array and converts it into a valid json string that will be read as a json object by javascript.

<?php

// create our php array - this will convert to a json object
$array = array(
	"name" => "darian",
	"lastname" => "brown",
	"age" => 87,
	"address" => array(
		"21 somewhere street",
		"my city",
		"Australia"
	)
);

// now we convert the above array to json string using json_encode()
$json = json_encode($array);

// set the json header content-type
header('Content-Type: application/json');
// and output the $json string so that it can be handled by our javascript code as a json object
echo $json;

// above echo will output our array as
//	'{"name":"darian","lastname":"brown","age":87,"adress":{"21 somewhere street","my city","Australia"}}'

?>