我有這個過分複雜的Eatec XML轉儲,很遺憾,每個菜單都有它自己的特殊屬性,用於在早餐/午餐/晚餐時間提供膳食。我試圖從他們的描述中提取物品,並做一個循環來顯示早餐的食譜,以及其他菜單時間等。嘗試獲取XML getElementsByTagName + getAttribute調用循環工作
這裏是瘦了一個示例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>';
而不是顯示在自己的循環早餐和午餐的飯菜,它的加載關於什麼是就餐時間每天的食譜。我是否過於複雜?我被自己的代碼迷失了?
感謝這個工作如預期!是的,我知道我很接近,但像你說的那樣完全糾結。 – user2510532
不客氣! – splash58