Skip to content
PHP Logo

What are the best practices for extracting links from HTML pages in PHP?

When extracting links from HTML pages in PHP, it is important to use a reliable HTML parsing library like DOMDocument to ensure accurate extraction. By using DOMDocument, you can easily navigate through the HTML structure and extract links based on specific criteria such as anchor tags. Regular expressions can also be used, but they are generally not recommended for parsing HTML due to its complexity and potential for errors.

php
// Create a new DOMDocument object
$dom = new DOMDocument();

// Load the HTML content from a file or a URL
$dom->loadHTMLFile('example.html');

// Get all anchor tags from the HTML content
$links = $dom->getElementsByTagName('a');

// Loop through each anchor tag and extract the href attribute
foreach ($links as $link) {
    $href = $link->getAttribute('href');
    echo $href . "\n";
}