Elegant little PHP JSON encoder
…so I wrote (what I think is a) clever little function (well, two functions) to take a complex php variable and turn it into a json-ized string, ready to be passed back to javascript. It works on the principle that json really only has a couple rules if text formatting: strings go inside double quotes, with both slashes and double-quotes escaped, iterative arrays are comma delimited inside brackets [obj1,obj2], and associative arrays go inside curly-brackets {key:val,key:val}. Using these three points, and a little bit (ok, a lot of) recursion, and voila, an elegant little function.
Of course, this doesn’t handle unicode, or any really special cases, but if you’re looking for a basic object parser, and you dont’ have access to php 5.2, which has it built into the language, it’ll do the trick…
/**
* input an object, returns a json-ized string of said object
* @return
* @param $obj Object
*/
function php_json_encode($obj) {
if (is_array($obj)) {
if (array_is_associative($obj)) {
$arr_out = array();
foreach ($obj as $key=>$val) {
$arr_out[] = '"' . $key . '":' . php_json_encode($val);
}
return '{' . implode(',', $arr_out) . '}';
} else {
$arr_out = array();
$ct = count($obj);
for ($j = 0; $j < $ct; $j++) {
$arr_out[] = php_json_encode($obj[$j]);
}
return '[' . implode(',', $arr_out) . ']';
}
} else {
if (is_int($obj)) {
return $obj;
} else {
$str_out = stripslashes(trim($obj));
$str_out = str_replace(array('"', '', '/'), array('\"', '\', '/'), $str_out);
return '"' . $str_out . '"';
}
}
}
function array_is_associative($array) {
$count = count($array);
for ($i = 0; $i < $count; $i++) {
if (!array_key_exists($i, $array)) {
return true;
}
}
return false;
}
