Simplexml get node by attribute

2019-05-31 15:12发布

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

标签: php simplexml
2条回答
叛逆
2楼-- · 2019-05-31 15:27

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;
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-05-31 15:32

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'
}
查看更多
登录 后发表回答