提问人:Maciek 提问时间:7/4/2023 更新时间:7/4/2023 访问量:36
PHP SimpleXML xpath 正在获取一个空数组
PHP SimpleXML Xpath Is Getting An Empty Array
问:
我正在尝试使用 xpath 函数从 XML 文件中获取信息。出于某种原因,它不断返回一个空数组。
XML 文件
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/>
<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>
<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>
<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://test.com/" TargetMode="External"/>
<Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
<Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://youtu.be/" TargetMode="External"/>
<Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://youtu.be/" TargetMode="External"/>
<Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://youtu.be/" TargetMode="External"/>
</Relationships>
做一个简单的
$relationships=simplexml_load_file('document.xml.rels');
print_r($relationships);
// prints full xml perfectly
print_r($relationships->xpath('//Relationship'));
// prints empty array: Array()
为什么打印一个空数组?$relationships->xpath('//Relationship')
例如,我的目标是通过使用来选择关系,但甚至不起作用?Id
->xpath('//Relationship[@Id="rId7"]')
->xpath('//Relationship')
注意:我也尝试过使用,但没有成功。var_dump()
答:
2赞
Sabin Chacko
7/4/2023
#1
由于 XML 文件中有一个命名空间 xmlns=“http://schemas.openxmlformats.org/package/2006/relationships”,因此需要在运行查询之前使用它进行注册。SimpleXMLElement::registerXPathNamespace()
更新的代码
$relationships=simplexml_load_file('document.xml.rels');
print_r($relationships);
// prints full xml perfectly
foreach($relationships->getDocNamespaces() as $strPrefix => $strNamespace) {
if(strlen($strPrefix)==0) {
$strPrefix="a"; //Assign an arbitrary namespace prefix.
}
$relationships->registerXPathNamespace($strPrefix,$strNamespace);
}
echo "<br><br>PRINTING<br><br>";
print_r($relationships->xpath('//a:Relationships'));
这将打印内容。Relationships
评论