Simple way to output JSON object in PHP

Provided you have PHP 5.2.0 or greater you will have the "json_encode" method.  If, like me however, you dont have version 5.3.0 or greater what you won't have is the second argument to this function - "options".  This allows you to force a particular JSON output style, such as array or object.

I wanted to output a JSON object, but rather than have to instantiate a stdobject and set a load of properties on it you can use PHP's cast construct to just cast an array into an object, like this:

$outputObject = (object) array(
'id'=>5,
'name'=>'test' 
); 
echo json_encode($outputObject);  

Because the argument to json_encode in now an object it will output a nice JSON object!

{ "id": 5, "name": "test" }