What are the best practices for extracting specific elements from HTML content in PHP using DOMDocument and XPath?

When extracting specific elements from HTML content in PHP using DOMDocument and XPath, it is important to first load the HTML content into a DOMDocument object and then use XPath queries to select the desired elements. It is recommended to use XPath expressions that target the specific elements needed, making the extraction process more efficient and accurate.

// HTML content to be parsed
$html = '<div id="container">
            <h1>Title</h1>
            <p>Paragraph 1</p>
            <p>Paragraph 2</p>
         </div>';

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

// Create a new DOMXPath object
$xpath = new DOMXPath($doc);

// XPath query to select all <p> elements within the <div> with id="container"
$elements = $xpath->query('//div[@id="container"]/p');

// Loop through the selected elements and output their text content
foreach ($elements as $element) {
    echo $element->textContent . "<br>";
}