What are some common methods in PHP to extract specific content from an HTML file?

When working with HTML files in PHP, you may need to extract specific content such as text, links, or images. One common method is to use regular expressions to search for patterns within the HTML code. Another approach is to use PHP's built-in DOMDocument class to parse the HTML and extract the desired elements based on their tags or attributes. Additionally, you can use third-party libraries like Simple HTML DOM Parser to simplify the process of extracting content from HTML files.

// Method 1: Using regular expressions
$html = file_get_contents('example.html');
preg_match('/<title>(.*?)<\/title>/', $html, $matches);
echo $matches[1]; // Output: The title of the HTML file

// Method 2: Using DOMDocument
$dom = new DOMDocument();
$dom->loadHTMLFile('example.html');
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
    echo $link->getAttribute('href') . "\n"; // Output: List of all links in the HTML file
}

// Method 3: Using Simple HTML DOM Parser
include('simple_html_dom.php');
$html = file_get_html('example.html');
$images = $html->find('img');
foreach ($images as $image) {
    echo $image->src . "\n"; // Output: List of all image sources in the HTML file
}