php - 如何解析xml并只显示有特定值的行?

时间:2014-08-19 09:15:30

标签: php xml

我有一个与此类似的xml:

<xml>
<products name="product_list">
<product id="1" name="product_1">Soap</product>
<product id="2" name="product 3">Shampoo</product>
<product id="3" name="product_3">Sponge</product>
</products>
</xml>

我正在尝试通过php(使用simplexml)导入它,但我想只显示一行,其中id匹配我设置的另一个变量。

类似的东西:

echo product where product['id'] = $variable 

但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

<?php

$xml = simplexml_load_string('<xml>
<products name="product_list">
<product id="1" name="product_1">Soap</product>
<product id="2" name="product 3">Shampoo</product>
<product id="3" name="product_3">Sponge</product>
</products>
</xml>');

$variable = 2;

foreach ($xml->products->product as $row) {
  if ((int)$row->attributes()->id === $variable) {
    echo ((string)$row);
  } // if
} // foreach

它将显示id为2的所有产品......