doujuchuan9915 2015-02-26 01:13
浏览 42
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dongshendi3599 2015-02-26 01:24
    关注

    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!";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析