JSON Structuring in PHP for Restful API

This is a basic guide on writing JSON response in PHP for Restful API. I often forgot how to structure it in PHP, so I'm writing this note to keep myself a reminder whenever I want to use it again.

Note: This is NOT a guide on how to write good JSON response

<?php

$news_obj = new stdClass();
$metadata = array('count' => 60);
// creating a single object
$news_obj->metadata = $metadata;
// arrays in object
$array = array('title'=>'herp', 'description'=>'derpity derp');
$array2 = array();
$array2['array1'] = 'value_array1';
$array2['array2'] = 'value_array2';
// putting arrays into an object
$news_obj->results[] = $array;
$news_obj->results[] = $array2;

// echo '<pre>'.json_encode($news_obj, JSON_PRETTY_PRINT).'</pre>';
echo pretty($news_obj);

function pretty($content) {
  return '<pre>'.json_encode($content, JSON_PRETTY_PRINT).'</pre>';
}

Response:

{
    "metadata": {
        "count": 60
    },
    "results": [
        {
            "title": "herp",
            "description": "derpity derp"
        },
        {
            "array1": "value_array1",
            "array2": "value_array2"
        }
    ]
}
Show Comments

Get the latest posts delivered right to your inbox.