Search code examples
phpsimplexml

How to use foreach to get the data using simplexml_load_string?


I have series of data in XML format as below:

<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>

I want to use a PHP code to display the data in the following format:

Saturday:

Breakfast is BREAKFAST1 with calorie of 1

Launch is LAUNCH1 with calorie of 3

Dinner is DINNER1 with calorie of 5

Sunday:

Breakfast is BREAKFAST2 with calorie of 1

Launch is LAUNCH2 with calorie of 7

Dinner is DINNER2 with calorie of 9

So, I started with the following PHP code to get the meals:

<?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";
}
}
}
?>

But the code does not print anything.

Where is the problem?


Solution

  • You might be better advised rearranging the structure of your XML, so that the name (e.g. BREAKFAST1) and the number of calories are in their own tags.

    <?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;
        }
    }