2024-10-17

抓取链接的 php 代码

抓取链接的 php 代码

要使用 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-&gt;getElementsByTagName('a');

    // Loop through the anchors and collect the href attributes
    foreach ($anchors as $anchor) {
        $href = $anchor-&gt;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;
}
?&gt;

</a>
登录后复制

以上就是抓取链接的 php 代码的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1051972.html

发表回复

Your email address will not be published. Required fields are marked *