How can PHP developers optimize their code to efficiently loop through an array of shopping cart items and format them correctly for output to an XML file?

To efficiently loop through an array of shopping cart items and format them for output to an XML file, PHP developers can use a combination of array functions like foreach and simplexml to create the XML structure. By iterating through each item in the array and adding the necessary elements to the XML, developers can easily generate the desired output.

// Sample array of shopping cart items
$cartItems = [
    ['id' => 1, 'name' => 'Product 1', 'price' => 10.99],
    ['id' => 2, 'name' => 'Product 2', 'price' => 19.99],
    ['id' => 3, 'name' => 'Product 3', 'price' => 5.99]
];

// Create a new SimpleXMLElement object
$xml = new SimpleXMLElement('<cart></cart>');

// Loop through each item in the array and add it to the XML
foreach ($cartItems as $item) {
    $product = $xml->addChild('product');
    $product->addChild('id', $item['id']);
    $product->addChild('name', $item['name']);
    $product->addChild('price', $item['price']);
}

// Output the XML
echo $xml->asXML();