当前位置:首页 > PHP教程 > php应用 > 列表

php5.2以下版本无json_decode函数的解决方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-01-10 20:56:58 浏览: 评论:0 

这篇文章主要介绍了php5.2以下版本无json_decode函数的解决方法,需要的朋友可以参考下,今天写代码的时候,需要用到json_decode函数,发现php5.2以前的版本没有集成这个函数,不过我们可以通过自定义函数实现,代码如下:

  1. function json_decode2($json) 
  2. { 
  3. $comment = false; 
  4. $out = '$x='; 
  5.  
  6. for ($i=0; $i<strlen($json); $i++) 
  7. { 
  8. if (!$comment) 
  9. { 
  10. if (($json[$i] == '{') || ($json[$i] == '[')) $out .= ' array('; 
  11. else if (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')'; 
  12. else if ($json[$i] == ':') $out .= '=>'; 
  13. else $out .= $json[$i]; 
  14. } 
  15. else $out .= $json[$i]; 
  16.  
  17. if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment; 
  18. } 
  19.  
  20.     eval($out . ';'); 
  21. return $x; 
  22. } 

不过这个返回的是Array,要返回object 则要用到 service_json类了。

Tags: php5 2 json_decode

分享到: