How can a foreach loop be effectively used to iterate through XML data in PHP and extract specific values?

To iterate through XML data in PHP and extract specific values, you can use a foreach loop to traverse through the XML nodes and access the desired elements. Within the loop, you can use functions like simplexml_load_string() to convert the XML data into an object that can be easily navigated. By accessing the object properties or attributes, you can extract the specific values needed from the XML data.

$xmlData = '<data>
    <item>
        <name>John Doe</name>
        <age>30</age>
    </item>
    <item>
        <name>Jane Smith</name>
        <age>25</age>
    </item>
</data>';

$xmlObject = simplexml_load_string($xmlData);

foreach ($xmlObject->item as $item) {
    $name = (string) $item->name;
    $age = (int) $item->age;
    
    echo "Name: $name, Age: $age" . PHP_EOL;
}