Simplexml get node by attribute

2019-05-31 14:53发布

问题:

I've got xml file:

<?xml version="1.0" ?>
<xml>
<opis lang="en">My text</opis>
<opis lang="cz">My text2</opis>
</xml>

I want to get "My text2" - so a node where attribute lang is "cz":

$xml = simplexml_load_file($fileName);
$result = $xml->xpath('//xml/opis[@lang="cz"]')

but instead of value I get:

array(1) (
  [0] => SimpleXMLElement object {
    @attributes => array(1) (
      [lang] => (string) cz
    )
  }
))

回答1:

Try using DomDocument:

$xml = new DomDocument;
$xml->load('yourFile');
$xpath = new DomXpath($xml);

foreach ($xpath->query('//xml/opis[@lang="cz"]') as $rowNode) {
  echo $rowNode->nodeValue; // will be 'this item'
}


回答2:

You could get the value like this:

$xml = simplexml_load_file($fileName);
$result = $xml->xpath('//xml/opis[@lang="cz"]');
foreach($result as $res) {
   echo $res;
}


标签: php simplexml