无法使用simplexml_load_string读取XML文件

时间:2011-10-02 09:49:58

标签: php xml xml-parsing simplexml

我一直在尝试读取xml文件,但它给了我一个奇怪的错误。 我的XML如下

<?xml version='1.0' encoding='UTF-8'?>
<response>
    <url>http://xyz.com</url>
    <token>xxxxxxx<token>
</response>

要阅读本文,我正在使用

simplexml_load_string(variable containing xml goes here)

但它给了我这个错误

  

警告:simplexml_load_string()[function.simplexml-load-string]:   实体:第1行:解析器错误:期望开始标记,'&lt;'找不到   第47行

     

警告:simplexml_load_string()[function.simplexml-load-string]:1   在第47行

     

警告:simplexml_load_string()[function.simplexml-load-string]:^   在第47行

3 个答案:

答案 0 :(得分:4)

Thanx所有的关注和回复, 但这个问题在其他地方撒了谎 在我的curl请求中,我没有将CURLOPT_RETURNTRANSFER设置为true,这导致XML不被记录在变量中,并且在某种程度上被打印在屏幕上,给出了它来自变量的错觉,但事实并非如此。 但是我将CURLOPT_RETURNTRANSFER设置为1,它现在给我正确的结果。 抱歉这个愚蠢的错误。 并且总而言之。

答案 1 :(得分:3)

您从API获得的响应不是格式正确/有效的XML:

<token>xxxxxxx<token>
              ^ missing /

由于这是一个API响应,您需要在Simplexml实际读取之前修复它。您可以使用tidy extension Docs来解决此问题:

$config = Array(
    'input-xml' => 1,
);
$xml = tidy_repair_string($xml, $config);

$xmlObj = simplexml_load_string($xml);

$doc = dom_import_simplexml($xmlObj)->ownerDocument;

$xpath = new DOMXpath($doc);

foreach($xpath->query('//token[not(node())]') as $node)
{
    $node->parentNode->removeChild($node);
}

echo $xmlObj->asXML();

这将通过首先修复未关闭的标记然后删除空的token元素来生成以下XML:

<?xml version="1.0" encoding="utf-8"?>
<response>
<url>http://xyz.com</url>
<token>xxxxxxx
</token>
</response>

相关:

答案 2 :(得分:0)

正如你正确指出的那样,CURLOPT_RETURNTRANSFER设置为1非常重要!

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0 ); // set to 1 for debugging
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return from sms server