【发布时间】:2016-07-08 09:14:13
【问题描述】:
我有这个由 Eatec 提供的过于复杂的 XML 转储,遗憾的是,每个菜单都有自己的特殊属性,用于早餐/午餐/晚餐。我正在尝试提取带有描述的项目并执行循环以仅显示早餐的食谱,以此类推其他菜单时段。
这是一个精简的 XML 示例
<data>
<menu name="location breakfast" servedate="20160626" location="food court 1" mealperiodname="Breakfast" >
<recipes>
<recipe id="5626935" category="HOT MORNING GRAINS" description="Oatmeal RD">
</recipe>
<recipe id="5371796" category="HOT MORNING GRAINS" description="Rice Brown RD">
</recipe>
</recipes>
</menu>
<menu name="location lunch" servedate="20160626" location="food court 2" mealperiodname="Lunch">
<recipes>
<recipe id="4430587" category="SOUPS" description="Soup Tomato w/Garden Vegetables">
</recipe>
<recipe id="4210899" category="SOUPS" description="Soup Beef Barley w/Vegetables">
</recipe>
</recipes>
</menu>
</data>
而且我对 PHP/XML 比较陌生,仍在尝试在这里学习我的绳索,这是我想出的,但无法将循环项目保持在它自己的用餐时间。
<?php
$menu = new DOMDocument();
$breakfast = 'Breakfast';
$lunch = 'Lunch';
$menu->load("http://amphl.org/test.xml");
// Get location name
$menu_get = $menu->getElementsByTagName("menu");
$location_name = $menu_get->item(0)->getAttribute("location");
$menu_period = $menu_get->item(0)->getAttribute("name");
// Get menus
$recipes = $menu->getElementsByTagName("menu");
$recipe_items = $menu->getElementsByTagName("recipe");
// echo tests
echo '<h3 class="location_date">'.$menu_period.'</h3>';
echo '<h3 class="location_date">'.$location_name.'</h3>';
echo '<div class="meal_items">';
// echo '<h3 class="food_name"> Breakfast </h3>';
foreach( $recipes as $recipe )
{
// Get recipe name
$recipe_type = $recipe->getAttribute("mealperiodname");
echo '<h3 class="location_date">'.$recipe_type.'</h3>';
if ($recipe_type == $breakfast) {
foreach( $recipe_items as $recipe_item )
{
$recipe_name = $recipe_item->getAttribute("description");
echo '<p class="item_list"><a alt="" href="#">'.$recipe_name.'</a></p>';
}
}
else if ($recipe_type == $lunch) {
foreach( $recipe_items as $recipe_item )
{
$recipe_name = $recipe_item->getAttribute("description");
echo '<p class="item_list"><a alt="" href="#">'.$recipe_name.'</a></p>';
}
}
}
echo '</div>';
它不是在自己的循环中显示早餐和午餐的餐点,而是加载有关用餐时间的每个食谱。我让它太复杂了吗?我被自己的代码迷路了吗?
【问题讨论】:
标签: php xml dom getelementsbytagname getattribute