为什么我的 REST API 得到无效字符



从几天开始,我的服务无法使用我的API获取的信息JSON 的格式正确,但当file_get_contents收到字符串时,它会在字符串前面添加一些字符。最后我发现这些无效字符是 ascii 239,187,191为什么它会改变这一点?我该怎么做才能避免这个问题?

服务器是一个丑陋的Windows服务器,我认为这种恐怖来自这里,但不确定,我不拥有它。API 在代码点火器上,不是我自己做的,客户端在我自己的框架上。

如果我使用以下代码在响应中搜索:

    $test = file_get_contents($test);
    for($i = 0 ; $i < strlen($test); $i++)
    {
        echo $i;
        echo " : ";
        echo $test[$i];
        echo " / ";
        echo ord($test[$i]);
        echo "<br>";
    }

    die;

我有这个结果:0 : �/2391 : �/1872 : �/1913 : c/994 : b/985 : s/1156 : A/977 : $/368 : 5/539 : c/9910 : 2/5011 : 3/51

接口端:

public function listeDossiers($token, $year, $month)
{
    $token=$this->hexToStr($token);
    $token = substr($token,3);
    $connexion = $this->ConnLabo_model->findByToken($token);
    if($connexion !== null){
        header('content-type:application/json');
        $liste = json_encode($this->RendezVous_model->findByLabo($connexion->id_user, $year, $month) );
        echo $liste;
        return;
    }

}

客户端

    $this->view->setTpl('Liste');
    $this->layout->year=$year;
    $this->layout->month=$month;
    $file = $this->restConfig['server'] . "/listeDossiers/" . $this->strToHex(trim($_SESSION['token'])) . '/' . $year . '/' . $month;
    //var_dump($file);die;
    $file = file_get_contents($this->restConfig['server'] . "/listeDossiers/" . $this->strToHex(trim($_SESSION['token'])) . '/' . $year . '/' . $month ) ;
    $this->view->liste = json_decode( $file);

我不确定,但可能是这个问题是由于字符集尝试使用

header('Content-Type: text/html; charset=utf-8');

在您的文件中。

我已经找到了解决方案,这是一个字符集错误的文件(带有 BOM 的 UTF8),我转换了该文件,现在没事了。

感谢您的帮助

最新更新