How can DOMDocument be utilized in PHP to manipulate HTML data efficiently compared to regex?
When manipulating HTML data in PHP, using DOMDocument is a more efficient and reliable method compared to regex. DOMDocument allows for parsing and manipulating HTML as a structured document, while regex can be error-prone and less flexible when dealing with complex HTML structures.
// Create a new DOMDocument object
$doc = new DOMDocument();
// Load the HTML content into the DOMDocument
$doc->loadHTML($html);
// Find elements using DOMXPath
$xpath = new DOMXPath($doc);
$elements = $xpath->query('//div[@class="example"]');
// Loop through the elements and manipulate them as needed
foreach ($elements as $element) {
// Manipulate the element here
}
// Save the modified HTML content
$modifiedHtml = $doc->saveHTML();