How can you optimize PHP code to handle multiple iterations and conditions when working with XML data?
When working with XML data in PHP, it's important to optimize your code to efficiently handle multiple iterations and conditions. One way to do this is by using SimpleXMLElement to parse the XML data and then loop through the elements to perform the necessary operations. Additionally, you can use conditional statements to check for specific conditions within the XML data and execute corresponding actions.
$xml = '<data>
<item>
<name>Item 1</name>
<price>10</price>
</item>
<item>
<name>Item 2</name>
<price>20</price>
</item>
</data>';
$items = new SimpleXMLElement($xml);
foreach ($items->item as $item) {
$name = (string) $item->name;
$price = (float) $item->price;
if ($price > 15) {
echo $name . ' is expensive!' . PHP_EOL;
} else {
echo $name . ' is affordable.' . PHP_EOL;
}
}