PHP前端开发

抓取链接的 php 代码

百变鹏仔 1个月前 (12-15) #PHP
文章标签 代码

要使用 php 从网页中抓取链接,您可以使用 file_get_contents 函数来获取 html 内容,然后使用 domdocument 类对其进行解析。这是一个简单的示例:站点:sportsfire

<?php// Function to scrape links from a given URLfunction 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 linksforeach ($links as $link) {    echo $link . PHP_EOL;}?>