Skip to content

Instantly share code, notes, and snippets.

@jmillerdesign
Created January 14, 2012 07:24
Show Gist options
  • Save jmillerdesign/1610602 to your computer and use it in GitHub Desktop.
Save jmillerdesign/1610602 to your computer and use it in GitHub Desktop.
Output a standardized JSON response for an API call
<?php
/**
* Output a JSON response for an API call
*
* @param array $data Data to return
* @param boolean|string $status Status type
* Available status types:
* - true (outputs 'ok')
* - false (outputs 'error')
* - ok
* - redirect
* - error
* @param array|string $opts Options for additional params
* Available options:
* - to: Where to redirect to
* - message: Text to output to user
*
* If $opts is a string, it will be used as 'to' for redirect or 'message' for others
* @return void (Halts rendering and outputs JSON response)
*/
function outputJSON($data = array(), $status = 'ok', $opts = array()) {
if ($status === true) {
$status = 'ok';
} else if ($status === false) {
$status = 'error';
}
// Convert $opts to array if it is a string
if ($opts && is_string($opts)) {
if ($status == 'redirect') {
$opts = array('to' => $opts);
} else {
$opts = array('message' => $opts);
}
}
if (($status == 'ok') || ($status == 'redirect')) {
header('Content-type: application/json');
} else {
header('Content-type: application/json', true, 400);
}
$response = array(
'status' => $status,
'data' => ($data === false) ? array() : $data
);
// Handle redirects
if (!empty($opts['to']) && ($status == 'redirect')) {
$response['to'] = $opts['to'];
}
// Handle messages
if (!empty($opts['message'])) {
$response['message'] = $opts['message'];
}
if (!empty($opts['htmlspecialchars'])) {
// To pass data through iframe, you will need to encode all html tags
die(htmlspecialchars(json_encode($response), ENT_NOQUOTES));
}
die(json_encode($response));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment