【问题标题】:Can't read an XML file with simplexml_load_string无法使用 simplexml_load_string 读取 XML 文件
【发布时间】:2011-11-29 08:28:24
【问题描述】:

标签: php xml xml-parsing simplexml


【解决方案1】:

感谢大家的关注和回复, 但问题出在其他地方 在我的 curl 请求中,我没有将 CURLOPT_RETURNTRANSFER 设置为 true,这导致 XML 没有记录在变量中,并且以某种方式打印在屏幕上,给人一种它来自变量的错觉,但事实并非如此。 但是我将 CURLOPT_RETURNTRANSFER 设置为 1,它现在给了我正确的结果。 对不起这个愚蠢的错误。 谢谢大家。

【讨论】:

    【解决方案2】:

    您从 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>
    

    相关:

    【讨论】:

    • 总是简单的事情。 >.
    【解决方案3】:

    正如您正确指出的那样,将 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      相关资源
      最近更新 更多