在xml PHP上有条件的内部循环

时间:2014-02-28 03:45:44

标签: php xml

我有这样的xml。有些物品价格较旧,有些物品没有。

<product>
    <item>
        <name>product 1</name>
        <price type="old">100</price>
        <price type="new">50</price>
    </item>
    <item>
        <name>product 2</name>
        <price type="old">100</price>
        <price type="new">50</price>
    </item>
    <item>
        <name>product 3</name>
        <price type="new">50</price>
    </item>
</product>

我想遍历每个项目但只能获得那些类型=&#34; old&#34;项目

2 个答案:

答案 0 :(得分:1)

可以使用xpath直接获取项目:

获取item文档元素

中的所有product个孩子

/product/item

具有price子元素

/product/item[price]

其中属性type的值为old

/product/item[price[@type="old"]]

示例:https://eval.in/106865

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$items = $xpath->evaluate('/product/item[price[@type="old"]]');
foreach ($items as $item) {
  var_dump(
    $xpath->evaluate('string(name)', $item)
  ); 
};

答案 1 :(得分:0)

尝试使用xpath

$xml = new SimpleXmlElement($str);
$result = $xml->xpath('/product/item');
$items = array();
foreach($result as $res){
  $price = $res->xpath('price');
  foreach($price as $p){
   if($p['type']=='old'){
     $items[] = $res;
   }
  }
}

请参阅演示here