Skip to content

Instantly share code, notes, and snippets.

@mmccollow
Created May 27, 2010 20:12
Show Gist options
  • Save mmccollow/416285 to your computer and use it in GitHub Desktop.
Save mmccollow/416285 to your computer and use it in GitHub Desktop.
<?php
/**
* json_encode() only takes an $option argument in PHP 5.3.0+
* We need the FORCE_JSON_OBJECT option, so we'll roll our
* own json_encode() on PHP < 5.3.0
* @author Matt McCollow <[email protected]>
*/
if(!defined('JSON_FORCE_OBJECT')) {
define('JSON_FORCE_OBJECT', 0x05); // just guessing at this value
}
define('ITEM_SEPARATOR', ', ');
define('KEY_SEPARATOR', ': ');
function get_json_encoder() {
if(version_compare(PHP_VERSION, '5.3.0') >= 0) {
$json_encode_func = 'json_encode';
} else {
$json_encode_func = 'my_json_encode';
}
return $json_encode_func;
}
function my_json_encode($value, $options = 0) {
if(empty($value)) { return ""; }
if(is_scalar($value)) {
return _json_encode_base_string($value);
}
if(is_object($value) || $options == JSON_FORCE_OBJECT) {
return "[" . _json_encode_object($value) . "]";
}
if(is_array($value)) {
return "[" . _json_encode_array($value) . "]";
}
}
function _json_encode_base_string($value) {
$to_escape = array(
'\\' => '\\\\',
'/' => '\\/',
'"' => '\\"',
'\b' => '\\b',
'\f' => '\\f',
'\n' => '\\n',
'\r' => '\\r',
'\t' => '\\t'
);
$chr_array = str_split($value);
foreach($chr_array as $chr) {
if(array_key_exists($chr, $to_escape)) {
$ret_str .= $to_escape[$chr];
} else {
$ret_str .= $chr;
}
}
return "\"" . $ret_str . "\"";
}
function _json_encode_array($values) {
// TODO: this does not support single-element arrays
foreach($values as $value) {
if(is_scalar($value)) {
$output .= _json_encode_base_string($value) . ITEM_SEPARATOR;
} else if(is_array($value)) {
$output .= "[" . _json_encode_array($value) . "]" . ITEM_SEPARATOR;
}
}
return rtrim($output, ", ");
}
function _json_encode_object($values) {
// TODO: this does not support single-element arrays
foreach($values as $key => $value) {
if(is_scalar($value)) {
$output .= _json_encode_base_string($key) . KEY_SEPARATOR . _json_encode_base_string($value) . ITEM_SEPARATOR;
} else if(is_array($value)) {
$output .= "{" . _json_encode_object($value) . "}" . ITEM_SEPARATOR;
}
}
return rtrim($output, ", ");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment