首页 > 解决方案 > 出现异常:调用 SimpleXMLElement 时无法将字符串解析为 XML

问题描述

我正在尝试解析这个 XML ( http://numismics.org/search/apis/getNuds?identifiers=1995.11.282 ) 并拉出下面的元素,但是当我调用 SimpleXMLElement 时,我得到:“异常:无法解析字符串作为 XML”(API 来自http://numismics.org/search/apis

以下是上面链接中 XML 的基本外观:

<nuds xmlns="http://nomisma.org/nuds" xmlns:mets="http://www.loc.gov/METS/" xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://nomisma.org/nuds http://nomisma.org/nuds.xsd" recordType="physical">

...deleted to shorten question

<digRep>
    <mets:fileSec>
        <mets:fileGrp USE="obverse">
            <mets:file USE="iiif">
                <mets:FLocat LOCYPE="URL" xlink:href="http://images.numismatics.org/collectionimages%2F19501999%2F1995%2F1995.11.282.obv.noscale.jpg"/>
            </mets:file>

...deleted to shorten question

        </mets:fileGrp>
    </mets:fileSec>
</digRep>
</nuds>

这是我在此示例中使用的测试代码

$detail = simplexml_load_file("http://numismatics.org/search/apis/getNuds?identifiers=1995.11.282");
$digRep = new \SimpleXMLElement($detail->nuds->digRep); //the slash before the SimpleXMLElement is required for Laravel
$digRep->registerXPathNamespace('c', 'http://www.loc.gov/METS');
$result = $digRep->xpath('//c:mets:fileSec');

foreach ($result as $title) {
  echo $title . "\n";
}

我想知道这是否与“ mets :fileSec”有关,但我不太确定在这种情况下“fileSec”是什么。

标签: phpxmlxml-parsing

解决方案


mets只是命名空间http://www.loc.gov/METS/xmlns:mets定义)的别名。这是非常好的 XML,如果直接调用,它会在浏览器中解析。我建议检查您是否真的可以使用 PHP (with file_get_contents()) 获取 XML,而不是一些错误消息。服务有时会为不同的用户代理返回不同的结果。


推荐阅读