Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
json_encode alternative for PHP < 5.2
<?php
if (!function_exists('json_encode'))
{
function json_encode($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[] = json_encode($v);
return '[' . join(',', $result) . ']';
}
else
{
foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
return '{' . join(',', $result) . '}';
}
}
}
?>
@micheldosprazeres

This comment has been minimized.

Copy link

commented Nov 13, 2013

good stuff!

@java168

This comment has been minimized.

Copy link

commented Mar 21, 2014

+1

@geworfener

This comment has been minimized.

Copy link

commented Jul 8, 2014

+1

@BrunoGiubilei

This comment has been minimized.

Copy link

commented Nov 25, 2014

all congratulations for you man! you save my day!

@carlosocarvalho

This comment has been minimized.

Copy link

commented Nov 5, 2015

+1

@vincentschuang

This comment has been minimized.

Copy link

commented Mar 14, 2018

line 42 should change to avoid bug
foreach ($a as $k => $v){ if(is_numeric($k)){ $result[] = '"'.myjson_encode($k).'":'.myjson_encode($v); }else{ $result[] = myjson_encode($k).':'.myjson_encode($v); } }

@ben-w-smith

This comment has been minimized.

Copy link

commented Aug 28, 2018

First, thanks for sharing this, you no doubt saved me a major headache today.
Second, mirroring @vincentschuang, I ran into a bug where your gist encodes int's as properties which is not allowed in json. To fix this I replace lines 22 & 23 with:

if (is_int($a)) { return '"'. $a . '"'; } return $a;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.