如何使用foreach获取使用simplexml_load_string的数据?

How to use foreach to get the data using simplexml_load_string?

我有一系列 XML 格式的数据,如下所示:

<food>
<saturday>
<breakfast>BREAKFAST1
<cal>1</cal>
</breakfast>
<launch>LAUNCH1
<cal>3</cal>
</launch>
<dinner>DINNER1
<cal>5</cal>
</dinner>
</saturday>

<sunday>
<breakfast>BREAKFAST2
<cal>7</cal>
</breakfast>
<launch>LAUNCH2
<cal>9</cal>
</launch>
<dinner>DINNER2
<cal>11</cal>
</dinner>
</sunday>
</food>

我想使用 PHP 代码以下列格式显示数据:

周六:

早餐是 BREAKFAST1,卡路里为 1

发射是 LAUNCH1,卡路里为 3

晚餐是 DINNER1,卡路里为 5

星期日:

早餐是 BREAKFAST2,卡路里为 1

发射是 LAUNCH2,卡路里为 7

晚餐是 DINNER2,卡路里为 9

所以,我开始使用以下 PHP 代码来获取餐点:

<?php
$food_data = "<food>
<saturday>
<breakfast>BREAKFAST1
<cal>1</cal>
</breakfast>
<launch>LAUNCH1
<cal>3</cal>
</launch>
<dinner>DINNER1
<cal>5</cal>
</dinner>
</saturday>

<sunday>
<breakfast>BREAKFAST2
<cal>7</cal>
</breakfast>
<launch>LAUNCH2
<cal>9</cal>
</launch>
<dinner>DINNER2
<cal>11</cal>
</dinner>
</sunday>
</food>";

$xml = simplexml_load_string($food_data);
foreach($xml as $key => $day)
{
foreach($xml->$key as $key2 => $meal)
{
foreach($xml->$key->$key2 as $key3 => $cal)
{
print "Day: $day and its time for: $meal and the calorie is $cal";
}
}
}
?>

但是代码没有打印任何东西。

问题出在哪里?

您最好重新安排 XML 的结构,以便名称(例如 BREAKFAST1)和卡路里数量在它们自己的标签中。

<?php

$food_data =  <<< EOL
<food>
<saturday>
<breakfast>
<name>BREAKFAST1</name>
<cal>1</cal>
</breakfast>
<launch>
<name>LAUNCH1</name>
<cal>3</cal>
</launch>
<dinner>
<name>DINNER1</name>
<cal>5</cal>
</dinner>
</saturday>

<sunday>
<breakfast>
<name>BREAKFAST2</name>
<cal>7</cal>
</breakfast>
<launch>
<name>LAUNCH2</name>
<cal>9</cal>
</launch>
<dinner>
<name>DINNER2</name>
<cal>11</cal>
</dinner>
</sunday>
</food>

EOL;

$xml = simplexml_load_string($food_data);
//var_dump($xml);
foreach($xml as $day_name => $day) {
    foreach($day as $meal_name => $meal) {
       print "Day: $day_name and its time for: $meal->name and the calorie is $meal->cal" . PHP_EOL;
    }
}