What are some common methods for extracting specific parts of HTML code in PHP scripts?

When working with HTML code in PHP scripts, it is common to need to extract specific parts of the code, such as specific elements or attributes. One common method for achieving this is by using PHP's DOMDocument class to parse the HTML and then using XPath queries to target and extract the desired elements.

// Sample HTML code
$html = '<div class="container">
            <h1>Hello, World!</h1>
            <p>This is a paragraph.</p>
         </div>';

// Create a new DOMDocument object
$dom = new DOMDocument();
$dom->loadHTML($html);

// Use XPath to query for specific elements
$xpath = new DOMXPath($dom);
$elements = $xpath->query('//h1');

// Extract and output the text content of the queried element
foreach ($elements as $element) {
    echo $element->nodeValue;
}