json_encode为UTF-8字符集返回null [英] json_encode returning null for UTF-8 charset
问题描述
我有一个像这样的json文件
I have a json file like this
{"downloads":[
{
"url":"arquivo1.pdf",
"descricao":"árquivo 1"
},
{
"url":"arquivo2.pdf",
"descricao":"arquivo 2"
}
]}
然后我通过 Notepad ++ 使用 UTF-8编码保存它.
And I save it using UTF-8 encode via Notepad++.
然后我得到文件内容:
function getContent($name)
{
$content = file_get_contents("configs/" . $name . ".json");
$encoded = utf8_encode($content);
return json_decode($encoded);
}
和json_decode
返回null
.
如果我将json文件另存为ANSI,那么它将起作用.但我想将其另存为UTF-8.
If I save the json file as ANSI then it works. But I'd like to save it as UTF-8.
推荐答案
我怀疑初始文件已采用UTF-8格式或格式错误.
I suspect that the initial file is either already in UTF-8 or in a badly formatted type.
如果无法解码json或编码的数据深于递归限制,则返回NULL .
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
编码错误
您可以通过执行以下操作来检查您的输入内容是否已经是有效的utf-8:
You can check if your input content is already valid utf-8 by doing this:
$is_valid_utf8 = mb_check_encoding($content, 'utf-8'));
如果是,请勿对其进行重新编码.
If it is, don't re-encode it.
文档提供了更多内容: http://php.net/mb-check-encoding
The documentation has more to offer: http://php.net/mb-check-encoding
BOM
或者Notepad ++设置的BOM可能会混淆json_decode
.
Or maybe Notepad++ sets a BOM which could confuse json_decode
.
//Remove UTF-8 BOM if present, json_decode() does not like it.
if(substr($content, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) {
$content = substr($content, 3);
}
请参见 json_decode
的文档.
see json_decode
's documentation.
这篇关于json_encode为UTF-8字符集返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!