php domdocument 获取节点值,其中属性值是

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6827871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:23:59  来源:igfitidea点击:

php domdocument get node value where attribute value is

phpattributesdomdocumentnodevalue

提问by Frits

Say my XML looks like this:

假设我的 XML 如下所示:

<record>
  <row name="title">this item</row>
  <row name="url">this url</row>
</record>

Now I'm doing something like this:

现在我正在做这样的事情:

$xml = new DOMDocument();
$xml->load('xmlfile.xml');

echo $xml->getElementByTagName('row')->item(0)->attributes->getNamedItem('title')->nodeValue;

But this just gives me:

但这只是给了我:

NOTICE: Trying to get property of non-object id

注意:试图获取非对象 id 的属性

Does anybody know how to get the node value where the "name" attribute has value "title"?

有人知道如何获取“name”属性值为“title”的节点值吗?

回答by Yoshi

Try:

尝试:

$xml = new DOMDocument();
$xml->loadXml('
<record>
  <row name="title">this item</row>
  <row name="url">this url</row>
</record>
');

$xpath = new DomXpath($xml);

// traverse all results
foreach ($xpath->query('//row[@name="title"]') as $rowNode) {
    echo $rowNode->nodeValue; // will be 'this item'
}

// Or access the first result directly
$rowNode = $xpath->query('//row[@name="title"][1]')->item(0);
if ($rowNode instanceof DomElement) {
    echo $rowNode->nodeValue;
}

回答by Liam Bailey

foreach ($xml->getElementsByTagName('row') as $element)
{
if ($element->getAttribute('name') == "title")
{
 echo $element->nodeValue;
}
}

回答by hashchange

$xpath = new DOMXPath( $xml );
$val = $xpath->query( '//row[@name="title"]' )->item(0)->nodeValue;