msgbartop
PHP源码分析,Zend引擎分析,Web相关技术研究,Web技术分享–左手代码 右手诗
msgbarbottom

02 Feb 10 注意PHP5.2.11之后的json_decode

在PHP5.2.6以前, json_decode一个字符串, 将会返回字符串本身.

php -r "var_dump(json_decode('laruence'));"
//输出
string(8)"laruence";

但是, 不知道是不是因为之前在php bug中, 有人提议对于这种情况, 因为字符串不是合法的json格式的串, 所以应该出错, 返回NULL(http://bugs.php.net/bug.php?id=45989). 所以在PHP5.2.11之后(具体是从哪个版本开始, 我回头再验证), 竟然返回NULL了.

php -r "var_dump(json_decode('laruence'));"
//输出
NULL

但值得注意的是, 对于numeric_string, 都是返回numeric_string的数值形式.

php -r "var_dump(json_decode('0x3f34'));"
//输出
int(16180)

另外, 在PHP5.3以后,可以通过json_last_error()来验证转换是否正确.

Related Posts:

Tags: , , ,

Reader's Comments

  1. |

    因为之前把几个PHP版本的安装路径搞混了, 看错了5.3的实现, 误以为5.3中和5.2.6一致, 抱歉给大家造成误解.

  2. |

    我在5.2.8下试了下。
    php -r “var_dump(json_decode(‘laruence’));”
    //输出
    string(8) “laruence”

  3. |

    @enjoy 我看到在5.2.9的release notes中有关于json_decode的, 但不是和这个相关的.

  4. |

    类似这样频繁改动的函数,我会重新写个函数。呵呵,虽然麻烦但兼容性相对好一些,而且一旦确定环境了,进行优化也相对容易一些^_^

  5. |

    guoxiaod@guoxiaod>php -r ‘var_dump(json_decode(“\”abc\”"));’
    string(3) “abc”
    guoxiaod@guoxiaod>php -v
    PHP 5.2.10-2ubuntu6.4 with Suhosin-Patch 0.9.7 (cli) (built: Jan 6 2010 22:41:56)

  6. |

    @anderson 不要”\”abc\”", 这里是指”abc”, ;)

  7. |

    json_encode 有没有类似这样的问题?

  8. |

    一般都会把这些封装到一个类,用静态方法调用,如
    JSON::decode()
    这样一来可以方便管理(归类、增加相关的方法),
    二来可以避免PHP升级后的接口变异。
    缺点是比直接调用原生的函数慢一点,但对比带来的可维护性的好处,这点效率牺牲完全可以忽略

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word