Simplexml get node by attribute

只愿长相守 提交于 2019-12-23 01:27: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
    )
  }
))

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


来源:https://stackoverflow.com/questions/15742457/simplexml-get-node-by-attribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!