PHP XML以非utf8格式返回


PHP XML being returned in non UTF 8

我使用以下函数将数据发送到特定的API。

function api_post($xml) {
    $ch = curl_init('http://api.asmx');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml;charset=UTF-8"));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    $results = curl_exec($ch);
    return $results;
}

输出为

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <LoadResponse xmlns="http://api.api.com/">
         <LoadResult>
             <date>2015-09-18T10_07_51.997</date>
             <data><br>⢠bullet1<br>⢠Bullet2</data>
         </LoadResult>
      </LoadResponse>
   </soap:Body>
</soap:Envelope>

返回的结果与预期一致,只是项目符号返回为â¢,日期值返回为2015-09-18T10_07_51.997而不是2015-09-18T10:07:51.997

当我在Soap UI中使用相同的XML测试相同的API调用时,所有内容都准确返回。我假设我在PHP中有某种编码问题。我该如何解决?

根据远程编码,您可以使用:

return utf8_encode($results);

你也可以试试

return utf8_decode($results);

注意:

如果您计划将utf-8输出到浏览器,您还可以使用以下命令:

<?php
//Teel the browser we'll be outputting UTF-8
header('Content-Type: text/html; charset=UTF-8');
// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding('UTF-8');
// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output('UTF-8');

根据您的评论更新

尝试将CURLOPT_ENCODING设置为"(空)并删除CURLOPT_HTTPHEADER,即:

curl_setopt($ch, CURLOPT_ENCODING, "");