Is there a general-purpose PHP JSON library that detects the level of JSON support in your version of PHP and calls on an externally-provided JSON library if native support is not found? ... or, am I going to be spending time writing this myself.
Facebook include one in their PHP Library. Hopefully they won't mind if you borrow it:
http://svn.facebook.com/svnroot/platform/clients/php/trunk/jsonwrapper/
I don't know of a full library out there, but I'm sure a little research could likely find one. However, here is a json_encode replacement that has served me well.
/**
* json_encode2()
*
* @access public
* @param bool $a
* @return string
*/
public function json_encode2($a=false) {
if (is_null($a)) return 'null';
if ($a === false) return 'false';
if ($a === true) return 'true';
if (is_scalar($a))
{
if (is_float($a))
{
// Always use "." for floats.
return floatval(str_replace(",", ".", strval($a)));
}
if (is_string($a))
{
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
}
else
return $a;
}
$isList = true;
for ($i = 0, reset($a); $i < count($a); $i++, next($a))
{
if (key($a) !== $i)
{
$isList = false;
break;
}
}
$result = array();
if ($isList)
{
foreach ($a as $v) $result[] = $this->json_encode2($v);
return '[' . join(',', $result) . ']';
}
else
{
foreach ($a as $k => $v) $result[] = $this->json_encode2($k).':'.$this->json_encode2($v);
return '{' . join(',', $result) . '}';
}
}
I think it's pretty easy, PHP < 5.2.0 = no JSON. There is the PECL JSON Library (the incarnation of the json functions before they were integrated in PHP) but that won't be of much use, either.
You could also check for function_exists("json_decode")
.
The User Contributed Notes to the JSON functions have some workaround implementations, e.g. here for the encode part. I don't know how reliable they are, though.
I used this:
$data = array();
$q = mysql_query("SELECT * FROM blah");
while ($r = mysql_fetch_array($q, MYSQL_ASSOC)) {
foreach ($r as $value) $data[] = '"' . addslashes($value) . '"';
}
echo '['.implode(', ', $data).']';
Gave the same results back as calling json_encode