PHP RegisterXPathNamespace - 来源不明的 XML 前缀

buc*_*112 2 php xml xpath simplexml

我对 PHP/XPath 还很陌生。我在 PHP 中使用 SimpleXML 和 XPath,通过名称空间遍历 XML。

我的问题是关于 registerXPathNamespace 函数中的“前缀”参数。
我的 xml feed 中有两个 xmlns;但是,我不确定在这种情况下如何使用该功能。
当我运行此代码时,我收到以下错误消息:

Undefined offset: 0
Run Code Online (Sandbox Code Playgroud)

我的 XML 无法以任何方式更改。请参阅下面的代码。感谢您提供任何线索。

PHP代码:

<?php
$url = 'test.xml';

$simplexml = simplexml_load_file($url);
//below, I'm uncertain as to what should be the prefix, 
//in the case of no apparent prefix in the xml - I've seen 'a' in other      
//examples (where the prefix does not exist in the xml), but unsure why.
$simplexml->registerXPathNamespace('a','http://www.digitalmeasures.com/schema/data');//
//below, as the 'dmd' prefix is in the xml, I've included it here.
$simplexml->registerXPathNamespace('dmd','http://www.digitalmeasures.com/schema/data-metadata');
//

$myDataObjects2 = $simplexml->xpath('//Record/INTELLCONT[@id="14"]/CONTYPE')[0];
//$myDataObjects2 = $simplexml->xpath('//Record/INTELLCONT/CONTYPE')[0];
echo $myDataObjects2;
?>
Run Code Online (Sandbox Code Playgroud)

XML:

<Data xmlns="http://www.digitalmeasures.com/schema/data" xmlns:dmd="http://www.digitalmeasures.com/schema/data-metadata" dmd:date="2018-01-03">
    <Record userId="148" username="john-doe" termId="44" dmd:surveyId="12">
        <dmd:IndexEntry indexKey="DEPARTMENT" entryKey="Toocas-CK" text="Toocas-CK"/>
        <INTELLCONT id="14" dmd:originalSource="MANUAL" dmd:lastModified="2017-02-21T15:21:45" dmd:startDate="2016-05-01" dmd:endDate="2016-07-31">
            <CONTYPE>Author Content</CONTYPE>
            <CONTYPEOTHER/>
            <NEWREV>Revised</NEWREV>
            <STATUS>Accepted</STATUS>
        </INTELLCONT>
    </Record>
</Data>
Run Code Online (Sandbox Code Playgroud)

spl*_*h58 5

您已注册命名空间

$simplexml->registerXPathNamespace('a','http://www.digitalmeasures.com/schema/data');
Run Code Online (Sandbox Code Playgroud)

并且您需要说 xpath 您正在查找的节点属于该名称空间

//a:Record/a:INTELLCONT[@id="14"]/a:CONTYPE
Run Code Online (Sandbox Code Playgroud)

演示

  • 该解决方案回答了您在注册命名空间方面的问题。你尝试过吗? (3认同)