Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php-如何解析xml并仅显示有特定值的行?_Php_Xml - Fatal编程技术网

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

php-如何解析xml并仅显示有特定值的行?,php,xml,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>

我有一个类似于以下内容的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

$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的所有产品…

您必须显示您尝试过的帮助吗?可能重复使用非常感谢!!!!我已经用答案中的xpath解决方案解决了这个问题。
<?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