What are the best practices for selecting specific elements with DOMDocument in PHP?

When using DOMDocument in PHP to parse HTML or XML documents, it is important to select specific elements efficiently and accurately. One common approach is to use XPath queries to target elements based on their attributes or structure within the document. By utilizing XPath expressions, developers can easily navigate the DOM tree and retrieve the desired elements.

// Load the HTML content into a DOMDocument
$html = '<html><body><div class="content"><h1>Title</h1><p>Paragraph</p></div></body></html>';
$dom = new DOMDocument();
$dom->loadHTML($html);

// Use XPath to select specific elements
$xpath = new DOMXPath($dom);
$elements = $xpath->query("//div[@class='content']/h1");

// Loop through the selected elements
foreach ($elements as $element) {
    echo $element->nodeValue; // Output: Title
}