PHP XML解析器 - 未找到属性时的Echo消息

Let's say I have the following xml file:

<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>

And I have a piece of php code that grabs this xml file and looks for type="pizza" only. Then it echoes the ingredient of every pizza it finds.

$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!";}
}

I would like it to echo "no pizzas found" when zero pizzas are found in the xml file. As expected, with the current php code I have, it echoes "pizza not found" over and over again for every type that is not pizza.

So if no pizzas are found at all then echo "no pizzas found" only once.

Try this:

$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!";
}