PHP XML解析器-找不到属性时回显消息


PHP XML parser - Echo message when attribute not found

假设我有以下xml文件:

<menu_items>
  <food type="pizza" ingredient="cheese"/>
  <food type="spaghetti" ingredient="tomatoes"/>
  <food type="pizza" ingredient="pepperoni"/>
  <food type="hamburger" ingredient="beef"/>
  <!-- etc. -->
</menu_items>

我有一段php代码,它获取了这个xml文件,只查找type="pizza"。然后,它会与它发现的每一个披萨的成分相呼应。

$url = "http://example.com/data.xml";
    $xml = simplexml_load_file($url);
foreach($xml->food as $food){
    If ($food["type"] == "pizza")
        {echo $food["ingredient"] . "<br>";}
    else
        {echo "No pizzas found!";}
}

当在xml文件中找不到披萨时,我希望它回复"没有找到披萨"。不出所料,在我现有的php代码中,对于每一个不是pizza的类型,它都会一次又一次地重复"pizza not found"。

因此,如果根本没有发现披萨,那么只重复一次"没有发现披萨"。

试试这个:

$url = "http://example.com/data.xml";
$xml = simplexml_load_file($url);
$pizzaflag = false;
foreach($xml->food as $food) {
    if ($food["type"] == "pizza") {
        echo $food["ingredient"] . "<br>";
        $pizzaflag = true;
    }
}
if ($pizzaflag == false) {
    echo "No pizzas found!";
}