php 确实会尝试产生错误,但只有在您关闭 display_errors 时。这很奇怪,因为display_errors 设置仅用于控制是否将错误打印到标准输出,而不是控制是否触发错误。我要强调的是,当你打开display_errors 时,即使你可能会看到各种其他的php 错误,php 并不仅仅隐藏这个错误,它甚至不会触发它。这意味着它不会出现在任何错误日志中,也不会调用任何自定义 error_handlers。错误永远不会发生。
这里有一些代码可以证明这一点:
error_reporting(-1);//report all errors
$invalid_utf8_char = chr(193);
ini_set('display_errors', 1);//display errors to standard output
var_dump(json_encode($invalid_utf8_char));
var_dump(error_get_last());//nothing
ini_set('display_errors', 0);//do not display errors to standard output
var_dump(json_encode($invalid_utf8_char));
var_dump(error_get_last());// json_encode(): Invalid UTF-8 sequence in argument
这种奇怪而不幸的行为与这个错误 https://bugs.php.net/bug.php?id=47494 和其他一些错误有关,而且看起来永远不会被修复。
解决方法:
在将字符串传递给 json_encode 之前清理字符串可能是一个可行的解决方案。
$stripped_of_invalid_utf8_chars_string = iconv('UTF-8', 'UTF-8//IGNORE', $orig_string);
if ($stripped_of_invalid_utf8_chars_string !== $orig_string) {
// one or more chars were invalid, and so they were stripped out.
// if you need to know where in the string the first stripped character was,
// then see http://stackoverflow.com/questions/7475437/find-first-character-that-is-different-between-two-strings
}
$json = json_encode($stripped_of_invalid_utf8_chars_string);
http://php.net/manual/en/function.iconv.php
说明书上说
//IGNORE 静默丢弃目标中的非法字符
字符集。
所以通过首先删除有问题的字符,理论上 json_encode() 不应该得到任何它会阻塞和失败的东西。我尚未验证带有 //IGNORE 标志的 iconv 的输出是否与有效 utf8 字符的 json_encodes 概念完全兼容,所以买家要小心……因为可能存在仍然失败的边缘情况。呃,我讨厌字符集问题。
编辑
在 php 7.2+ 中,json_encode 似乎有一些新标志:
JSON_INVALID_UTF8_IGNORE 和 JSON_INVALID_UTF8_SUBSTITUTE
目前还没有太多的文档,但现在,这个测试应该可以帮助你理解预期的行为:
https://github.com/php/php-src/blob/master/ext/json/tests/json_encode_invalid_utf8.phpt
而且,在 php 7.3+ 中有新标志 JSON_THROW_ON_ERROR。见http://php.net/manual/en/class.jsonexception.php