要使用 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中文網其他相關文章!