What are the advantages of using an XML parser like DOMDocument over regex for processing XML files in PHP?
When processing XML files in PHP, using an XML parser like DOMDocument is preferred over regex because XML parsers are specifically designed to handle the complexities of XML structure, ensuring accurate and reliable parsing. Regex, on the other hand, may not be able to handle all edge cases and can lead to errors or incorrect parsing of the XML data.
$xmlString = '<data><item>Item 1</item><item>Item 2</item></data>';
$dom = new DOMDocument();
$dom->loadXML($xmlString);
$items = $dom->getElementsByTagName('item');
foreach ($items as $item) {
echo $item->nodeValue . "\n";
}