json_encode() function for PHP 4 compatibility


/ Published in: PHP
Save to your folder(s)

Credits go to Steve at the URL shown


Copy this code and paste it in your HTML
  1. if (!function_exists('json_encode'))
  2. {
  3. function json_encode($a=false)
  4. {
  5. if (is_null($a)) return 'null';
  6. if ($a === false) return 'false';
  7. if ($a === true) return 'true';
  8. if (is_scalar($a))
  9. {
  10. if (is_float($a))
  11. {
  12. // Always use "." for floats.
  13. return floatval(str_replace(",", ".", strval($a)));
  14. }
  15.  
  16. if (is_string($a))
  17. {
  18. static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
  19. return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
  20. }
  21. else
  22. return $a;
  23. }
  24. $isList = true;
  25. for ($i = 0, reset($a); $i < count($a); $i++, next($a))
  26. {
  27. if (key($a) !== $i)
  28. {
  29. $isList = false;
  30. break;
  31. }
  32. }
  33. $result = array();
  34. if ($isList)
  35. {
  36. foreach ($a as $v) $result[] = json_encode($v);
  37. return '[' . join(',', $result) . ']';
  38. }
  39. else
  40. {
  41. foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
  42. return '{' . join(',', $result) . '}';
  43. }
  44. }
  45. }

URL: http://usphp.com/manual/en/function.json-encode.php#82904

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.