PHP SimpleXML调用Xpath返回空数组的原因及解决咨询
问题原因
你的XML文档带有默认命名空间(xmlns="http://schemas.openxmlformats.org/package/2006/relationships"),所有<Relationship>元素都属于这个命名空间。SimpleXML的XPath查询默认不会自动识别该命名空间,直接使用//Relationship会找不到任何元素——因为查询的是无命名空间下的<Relationship>,而实际元素属于指定命名空间。
解决方案
有两种可行的解决方式:
方法1:注册命名空间并使用前缀查询
先为命名空间注册一个自定义前缀,然后在XPath中通过前缀指定元素所属的命名空间:
$relationships = simplexml_load_file('document.xml.rels'); // 注册命名空间,前缀可自定义(示例用"rel") $relationships->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships'); // 查询所有Relationship元素 print_r($relationships->xpath('//rel:Relationship')); // 按Id筛选指定的Relationship $result = $relationships->xpath('//rel:Relationship[@Id="rId7"]'); print_r($result);
方法2:使用local-name()忽略命名空间
如果不想注册命名空间,可通过XPath的local-name()函数匹配元素的本地名称(不含命名空间部分):
$relationships = simplexml_load_file('document.xml.rels'); // 查询所有本地名称为Relationship的元素 print_r($relationships->xpath('//*[local-name()="Relationship"]')); // 按Id筛选指定元素 $result = $relationships->xpath('//*[local-name()="Relationship" and @Id="rId7"]'); print_r($result);
注意事项
- 方法1更规范,适合存在多命名空间的场景,能避免元素名称冲突;
- 方法2属于临时解决方案,若XML中存在同名不同命名空间的元素,可能会出现误匹配。
内容的提问来源于stack exchange,提问作者Maciek
相关产品推荐
相关产品推荐

