【问题标题】:PHP Receive JSON but can't decode itPHP接收JSON但无法解码
【发布时间】:2013-05-15 06:18:36
【问题描述】:

我在 PHP 中收到 JSON 代码,但如果我尝试对其进行解码,则没有任何反应。

代码:

$json = stripslashes($_POST['json']);
$output = json_decode($json);

当我将$json$output 登录到控制台时:

$json 值为:

{"post":"{'newfavorite':'<div id="1" class="favorite"><sub class="minID">Id 1</sub><a href="http://www.youtube.com/watch?v=1PXQpWm_kq0">http://www.youtu</a><span onclick="movefavorite(1)"><img class="move" title="Move" src="icon/move.png"></span><span onclick="removefavorite(1)"><img class="delete" title="Delete" src="icon/del.png"></span></div>','username':'ifch0o'}"}

$output 值为:空字符串或 null 或未定义。我不知道。

控制台说:output is :

【问题讨论】:

  • JSON 无效;你有不正确的嵌套引号
  • json 输入无效。 PHP 无法验证它,任何其他语言的任何其他 JSON 解码器也无法验证。将您的代码粘贴到 this one 之类的验证器中以供证明。
  • 这里的教训是使用适当的 json 编码器来生成 json,而不是自己构建它。您需要修复输入;在 PHP 端你无能为力来修复它。 (如果这个 json 来自第三方,那么你需要抱怨他们不是很好)
  • 首先验证您的 json。您可以使用以下网站:jsonlint.com 来确保您的 json 有效。
  • 如果斜杠没有被去掉,这个 JSON 是有效的...

标签: php json post decode


【解决方案1】:

您的 JSON 使用 " 表示字符串,但您的内容包含 " 例如

<div id="1" class="favorite">

因为您已经删除了使用 stripslashes() 转义的字符,所以字符串提前结束,这会创建无效的 JSON。

只需删除 stripslashes() 即可使这些字符转义。

$json = $_POST['json'];
$output = json_decode($json);

这就是 PHP 看到你的 JSON 的方式:

{
   "post": "{'newfavorite':'<div id=",
   1 // Error here - unexpected 1
   " class=" // unexpected string
   ...
}

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2016-06-12
    • 2017-05-12
    • 2023-03-11
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多