2011-01-06 165 views
0

我想在php下載一個文件。如何從HTML頁面提取鏈接?

$file = file_get_contents($url); 

我應該怎麼下載$網址的文件中的鏈接的內容...

+0

通過調用file_get_contents將鏈接作爲參數傳遞來下載鏈接。 – Oswald 2011-01-06 15:25:05

+0

[解析HTML的最佳方法]的可能重複(http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662) – Gordon 2011-01-06 15:27:29

回答

0

你需要解析生成的HTML字符串,可以手動或通過第三方插件。

HTML Scraping in Php

+0

謝謝Dutchie432 ... – 2011-01-06 15:30:22

2

這需要解析HTML,這是在PHP相當大的挑戰。爲了節省很多麻煩,請下載HTML解析庫,例如PHPQuery(http://code.google.com/p/phpquery/)。然後,您必須選擇所有與pq('a')的鏈接,通過它們循環獲取它們的href屬性值,併爲每個鏈接將其從相對轉換爲絕對,並在生成的URL上運行file_get_contents。希望這些指針能讓你開始。

1

所以你想找到給定文件中的所有URL?正則表達式來救援......而在其下面一些示例代碼應該做你想要什麼:

$file = file_get_contents($url); 
if (!$file) return; 
$file = addslashes($file); 

//extract the hyperlinks from the file via regex 
preg_match_all("/http:\/\/[A-Z0-9_\-\.\/\?\#\=\&]*/i", $file, $urlmatches); 

//if there are any URLs to be found 
if (count($urlmatches)) { 
    $urlmatches = $urlmatches[0]; 
    //count number of URLs 
    $numberofmatches = count($matches); 
    echo "Found $numberofmatches URLs in $url\n"; 

    //write all found URLs line by line 
    foreach($urlmatches as $urlmatch) { 
     echo "URL: $urlmatch...\n"; 
    } 
} 

編輯:當我正確地理解你的問題,你現在要下載的發現URL的內容。您可以在foreach循環中爲每個URL調用file_get_contents,但您可能需要事先進行一些篩選(如不要下載圖像等)。