php json_encode非空数组但结果为空

一个很奇怪的问题,

<?php
header("Content-type:text/html;charset=utf8");
echo $str=file_get_contents("country.txt");
echo $str;

>

文本数据如下:

巴基斯坦
菲律宾
新加坡

格式ascii格式。

最开始乱码,想了下,把文本改为utf-8无bom格式,显示还是乱码,但是加上一句:

$str=iconv("gb2312","utf-8",$str);

显示就正常了。

最开始乱码时json_encode

$countryArr=file("country.txt",FILE_IGNORE_NEW_LINES);
echo json_encode($countryArr);

显示了的是:

[null,null,null,null,null】

不乱码后json_encode正常了

最终代码:

<?php
header("Content-type:text/html;charset=utf8");
 $str=file_get_contents("country.txt");
//iconv('gbk', 'utf-8', $str);
$str=iconv("gb2312","utf-8",$str);
$arr=explode("\n",$str);
for($i=0;$i<count($arr);$i++)
{
    $arr[$i]=rtrim($arr[$i]);
}

echo json_encode($arr,JSON_UNESCAPED_UNICODE);

  
?>
原文地址:https://www.cnblogs.com/youxin/p/2936744.html