What potential pitfalls might arise when using foreach loops in PHP for XML parsing?

One potential pitfall when using foreach loops for XML parsing in PHP is that it may not handle nested elements properly, leading to incorrect data extraction or missing information. To solve this, you can use PHP's SimpleXMLElement class to navigate through the XML structure and access elements and attributes accurately.

$xml = '<root>
    <item>
        <name>Item 1</name>
        <price>10</price>
    </item>
    <item>
        <name>Item 2</name>
        <price>20</price>
    </item>
</root>';

$items = new SimpleXMLElement($xml);

foreach ($items->item as $item) {
    $name = (string) $item->name;
    $price = (float) $item->price;
    
    echo "Name: $name, Price: $price" . PHP_EOL;
}