What are the best practices for sorting and extracting specific elements from HTML code in PHP?

When sorting and extracting specific elements from HTML code in PHP, it is best to use a combination of DOMDocument and DOMXPath classes. DOMDocument is used to load the HTML content, while DOMXPath is used to query and extract specific elements based on XPath expressions. By utilizing these classes, you can easily navigate and manipulate the HTML structure to extract the desired information.

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

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

// Loop through the extracted elements and output their content
foreach ($elements as $element) {
    echo $element->nodeValue; // Output: Title
}