Frits
Frits

Reputation: 171

php domdocument get node value where attribute value is

Say my XML looks like this:

<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

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

Upvotes: 17

Views: 48302

Answers (3)

Yoshi
Yoshi

Reputation: 54659

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;
}

Upvotes: 17

hashchange
hashchange

Reputation: 7225

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

Upvotes: 3

Liam Bailey
Liam Bailey

Reputation: 5905

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

Upvotes: 16

Related Questions