我正在测试使用以下代码返回XML的终结点,我能够获取和转换XML并将其转换为对象
$url = "http://myendpoint.com/payload" //just a sample URL, confidential
$opts = array('http' => array('header' => 'Accept-Charset: UTF-8, *;q=0'));
$context = stream_context_create($opts);
$output = file_get_contents($url, false, $context);
$xml = simplexml_load_string($output);
碰巧的是,我们的数据库中包含肯定具有不同字符集的外语。现在,使用上面的代码,我能够正确检索输出。但是,我发现file_get_contents()
花费了太多时间,因此我决定使用cURL。
向您展示我的示例代码:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
$output = curl_exec($ch);
$xml = simplexml_load_string($output);
问题是外语或无法识别的字符,它一直在说
PCDATA无效的Char值8
我非常确定这是因为我无法将这些文本或字符转换为 UTF-8 可读格式
我尝试的一种修复方法是添加以下代码,以模仿我的file_get_contents()
技术:
$headers = array(
"Accept-Charset: UTF-8, *;q=0"
);
//cURL code
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
但无济于事,问题仍然存在
如何解决此问题?一直在花我的时间来调试此错误。