What are some common methods for filtering and extracting specific content from HTML pages using PHP?

When working with HTML pages in PHP, it is often necessary to filter and extract specific content from the page. This can be achieved using various methods such as regular expressions, DOMDocument, and libraries like SimpleHTMLDom. These methods allow you to parse the HTML structure and extract the desired content efficiently.

// Using DOMDocument to extract specific content from HTML
$html = file_get_contents('https://www.example.com');
$dom = new DOMDocument();
$dom->loadHTML($html);

// Extracting all <a> tags from the HTML
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
    echo $link->getAttribute('href') . PHP_EOL;
}

// Extracting specific content based on class name
$elements = $dom->getElementsByClassName('specific-class');
foreach ($elements as $element) {
    echo $element->nodeValue . PHP_EOL;
}