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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题