【问题标题】:json_encode returns NULL, json_last_error_msg gives "Control character error, possibly incorrectly encoded"json_encode 返回 NULL,json_last_error_msg 给出“控制字符错误,可能编码不正确”
【发布时间】:2014-06-19 17:22:29
【问题描述】:

读入我的编辑器时文件看起来很好。

$file = file_get_contents('path/to/file.json');
$json =  json_decode($file, true);
var_dump($json); // null
echo json_last_error_msg(); //Control character error, possibly incorrectly encoded

关于此错误消息的含义并不多。

【问题讨论】:

  • 能否请您发布您的file.json ?因为json_decode 无法从文件中解码您的 json 字符串。
  • 这意味着您的文件不包含有效的 JSON。

标签: php json


【解决方案1】:

您可以删除control character,PCRE 支持字符类[:cntrl:] 的POSIX 表示法

$json = preg_replace('/[[:cntrl:]]/', '', $json);
$json = json_decode($json, true);
var_dump($json);
echo json_last_error_msg();

【讨论】:

  • 一般来说,这是错误的做法。想象一下,您有以下字符串:“hello\nworld”,其中 \n 是非转义 (0x0a) 字符。 preg_replace 将修复它,尽管您将继续使用“helloworld”。应该修复生成 json 编码字符串的代码。
猜你喜欢
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 2018-02-28
相关资源
最近更新 更多