
要使用 php 从网页中抓取链接,您可以使用 file_get_contents 函数来获取 html 内容,然后使用 domdocument 类对其进行解析。这是一个简单的示例:站点:sportsfire
<?php
// Function to scrape links from a given URL
function scrapeLinks($url) {
// Get the HTML content of the webpage
$html = file_get_contents($url);
// Create a new DOMDocument instance
$dom = new DOMDocument();
// Suppress errors due to malformed HTML
libxml_use_internal_errors(true);
// Load the HTML content
$dom->loadHTML($html);
// Clear the errors
libxml_clear_errors();
// Create an array to hold the links
$links = [];
// Get all <a> elements
$anchors = $dom->getElementsByTagName('a');
// Loop through the anchors and collect the href attributes
foreach ($anchors as $anchor) {
$href = $anchor->getAttribute('href');
// Add the link to the array if it's not empty
if (!empty($href)) {
$links[] = $href;
}
}
return $links;
}
// Example usage
$url = 'https://www.example.com'; // Change this to the URL you want to scrape
$links = scrapeLinks($url);
// Print the scraped links
foreach ($links as $link) {
echo $link . PHP_EOL;
}
?>
以上就是抓取链接的 php 代码的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号