How can PHP be used to extract links from a specific URL, such as index.html?
To extract links from a specific URL like index.html using PHP, you can use the file_get_contents() function to retrieve the contents of the webpage and then use regular expressions or a DOM parser like SimpleXMLElement or DOMDocument to extract the links from the HTML.
$url = 'http://www.example.com/index.html';
$html = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($html);
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
echo $link->getAttribute('href') . "\n";
}
Related Questions
- What are the potential pitfalls of including markup and inline styles in PHP class constants?
- What are the potential pitfalls of comparing values with strings instead of numbers in PHP?
- How can the error "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given" be resolved when fetching results in PHP?