When should the DOMDocument class be used for manipulating HTML/XML content in PHP?

The DOMDocument class in PHP should be used when you need to manipulate HTML or XML content in a structured and reliable way. It provides a powerful set of methods for creating, editing, and traversing document objects, making it ideal for tasks such as parsing and modifying HTML documents.

// Create a new DOMDocument object
$doc = new DOMDocument();

// Load HTML content from a file
$doc->loadHTMLFile('example.html');

// Get all <a> tags in the document
$links = $doc->getElementsByTagName('a');

// Loop through each <a> tag and print the href attribute
foreach ($links as $link) {
    echo $link->getAttribute('href') . "\n";
}