Skip to content

Instantly share code, notes, and snippets.

@chrismademe
Last active December 23, 2017 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismademe/fcf2d2c5fe6a69e3510651e259c45389 to your computer and use it in GitHub Desktop.
Save chrismademe/fcf2d2c5fe6a69e3510651e259c45389 to your computer and use it in GitHub Desktop.
JSON output Class
<?php
class JSON {
// Options array
private $options = array();
/**
* Construct
*
* @param $options
*/
public function __construct( array $options = array() ) {
// Default options
$default = array(
'echo' => true,
'exit' => true,
'setHeader' => true
);
// Set options
$this->options = array_merge( $default, $options );
}
/**
* Output
*
* @param mixed $data Data output
* @param int $code HTTP Response Code
*/
public function output( $data, $code = 200 ) {
// Codes
$codes = array(
200 => 'OK',
201 => 'Created',
204 => 'No Content',
400 => 'Bad Request',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed'
);
// Validate code
if ( !array_key_exists($code, $codes) ) {
throw new Exception('JSON Error: Unsupported HTTP Response Code');
}
// Add Code to Response
$response['code'] = $code;
$response['status'] = $codes[$code];
// Add Data
$response['data'] = $data;
// Set Status code
http_response_code($code);
// Convert to JSON
$json = json_encode($response);
// Set JSON Header?
if ( $this->options['setHeader'] === true ) {
header('Content-type: application/json');
}
// Echo?
if ( $this->options['echo'] === true ) {
echo $json;
}
// Exit?
if ( $this->options['exit'] === true ) {
exit;
}
return $json;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment