PHP: json_encode before 5.2.0

Even though it is a lot of talks about PHP 5.3 there are still many production environments which run PHP 5.1.*. As well as sometimes development servers are updated earlier than production ones for testing purposes. It may cause that some new PHP features will not work on production because of older version there.

One of the most common examples is ‘missing’ json_encode() function which became native with PHP 5.2.0 onward. Below is possible workaround while your production has not upgraded yet.

<?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) . '}';
    }
  }
}
?>

Update: the same code is now available through GitHub.

7 Comments so far

  1. hristo on January 9th, 2010

    Thanks!

  2. Rodolfo on May 5th, 2011

    Thank you very much.

  3. Shweta on November 16th, 2011

    Thanks a lot…it saved my day 🙂

  4. dndn1011 on December 17th, 2011

    Thanks a lot for your help!

    -Dino

  5. Binod on March 18th, 2013

    How to echo the json_encode array. I have two rows in table.
    [{“id”:”1″,”username”:” Binod “,”email”:”ur_binod@yahoo.com “,”message”:”ches “,”date”:”18th March, 2013″,”time”:”12:00 am”},
    {“id”:”2″,”username”:” Binod “,”email”:”ur_binod@yahoo.com “,”message”:”ches “,”date”:”18th March, 2013″,”time”:”12:00 am”}]

  6. Alex on March 29th, 2013

    Not sure what you are looking, something like print_r()?

  7. alberto on April 20th, 2015

    Thanks a lot, Very good function!

Leave a reply