php - 出现异常:调用 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”是什么。
解决方案
mets
只是命名空间http://www.loc.gov/METS/
(xmlns:mets
定义)的别名。这是非常好的 XML,如果直接调用,它会在浏览器中解析。我建议检查您是否真的可以使用 PHP (with file_get_contents()
) 获取 XML,而不是一些错误消息。服务有时会为不同的用户代理返回不同的结果。
推荐阅读
- r - 如何为来自两个因素的水平的每个独特组合创建直方图?
- firebase-hosting - 无法使用自定义域将 Firebase 动态链接添加到项目
- python - 在 Python matplotlib 中更改 X 轴步长
- redirect - 如何检查我的页面是否来自 302 重定向?
- windows - Windows 7 和 10 - 在命令行更改文件/文件夹所有权,但不仅仅是我自己
- unity3d - Unity3d Animation - 如何让玩家在动画完成后停留在目标位置
- vue.js - 动态实例化的 Vue 组件如何被缓存?
- html - Magento HTML问题 - 侧栏出现在页面内容下方
- git - Git 将已存在的文件显示为新文件
- react-native - 如何在 defaultNavigationOptions 上添加订阅