Simplexml按属性获取节点

时间:2013-04-01 11:20:13

标签: php simplexml

我有xml文件:

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

我想获得“我的text2” - 所以属性lang为“cz”的节点:

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

但不是价值我得到:

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

2 个答案:

答案 0 :(得分:1)

你可以得到这样的价值:

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

答案 1 :(得分:0)

尝试使用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'
}