How can PHP be used to extract specific elements from an HTML page?

To extract specific elements from an HTML page using PHP, you can utilize the DOMDocument class to parse the HTML and then use XPath queries to target and extract the desired elements based on their attributes or structure.

// Load the HTML content from a file or URL
$html = file_get_contents('example.html');

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

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

// Use XPath query to extract specific elements (e.g. all <a> tags with class 'link')
$elements = $xpath->query("//a[@class='link']");

// Loop through the extracted elements and do something with them
foreach ($elements as $element) {
    echo $element->nodeValue . "<br>";
}