What is the best approach to extract and list all links in a webpage using PHP?

To extract and list all links in a webpage using PHP, you can use the DOMDocument class to parse the HTML content of the webpage and then iterate through all the anchor tags to extract the links. You can then store these links in an array and display them as a list.

<?php
// URL of the webpage to extract links from
$url = 'https://www.example.com';

// Create a new DOMDocument object
$doc = new DOMDocument();

// Load the HTML content from the webpage
$doc->loadHTMLFile($url);

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

// Iterate through each anchor tag and extract the href attribute
foreach ($links as $link) {
    $href = $link->getAttribute('href');
    echo "<a href='$href'>$href</a><br>";
}
?>