0

I know there have been other topics regarding this error, but I'm asking how do I confirm if this is available on my hosted server and if it isn't how do I add it:

phpinfo returns:

PHP Version 5.5.14
JSON    Omar Kilani, Scott MacVicar

Yet my error log shows: PHP Fatal error: Call to undefined function json_encode() in

I thought 5.5.14 should have included JSON ?

Thanks

Tom
  • 1,436
  • 24
  • 50

2 Answers2

2

Just install the JSON package with PECL because not every PHP distribution has the JSON package due to licensing restrictions.

Installation instructions here

Community
  • 1
  • 1
Szántó Zoltán
  • 981
  • 1
  • 12
  • 26
0

Here's what I've used successfully for PHP 5.1

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

  function json_decode($json) 
  {  

    $comment = false; 
    $out = '$x='; 

    for ($i=0; $i<strlen($json); $i++) 
    { 
        if (!$comment) 
        { 
            if ($json[$i] == '{' || $json[$i] == '[')        $out .= ' array('; 
            else if ($json[$i] == '}' || $json[$i] == ']')    $out .= ')'; 
            else if ($json[$i] == ':')    $out .= '=>'; 
            else                         $out .= $json[$i];            
        } 
        else $out .= $json[$i]; 
        if ($json[$i] == '"')    $comment = !$comment; 
    } 
    eval($out . ';'); 
    return $x; 
} 
ndrwnaguib
  • 5,623
  • 3
  • 28
  • 51
  • 1
    I would suggest using built-in functions instead. There is no guarantee that custom solutions can handle all edge cases and are safe from exploits. – Eriks Klotins Sep 25 '19 at 12:07