2010-02-15 93 views
5

我正在編寫一個網站爬蟲在php中,我已經有了可以從網站中提取所有鏈接的代碼。 問題:網站使用絕對和相對網址的組合。 實例(HTTP與hxxp代替,我不能發佈超鏈接):php將所有鏈接轉換爲絕對網址

hxxp://site.com/

site.com

site.com/index.php

hxxp://site.com/hello/index.php

/hello/index.php

hxxp://site2.com/index.php

site2.com/index.php

我無法控制鏈接(如果它們是絕對/相對的),但我確實需要關注它們。我需要將所有這些鏈接轉換爲絕對URL。我如何在PHP中執行此操作?

+2

你用什麼來解析html並找到鏈接?您的圖書館可能已經有辦法解析相關網址。 – 2010-02-15 20:08:39

+0

我使用我自己的HTML鏈接提取功能。除了curl和php函數外,我沒有使用任何庫。 – 2010-02-15 20:48:12

回答

5

這裏是一個開始

// Your crawler was sent to this page. 
$url = 'http://example.com/page'; 

// Example of a relative link of the page above. 
$relative = '/hello/index.php'; 

// Parse the URL the crawler was sent to. 
$url = parse_url($url); 

if(FALSE === filter_var($relative, FILTER_VALIDATE_URL)) 
{ 
    // If the link isn't a valid URL then assume it's relative and 
    // construct an absolute URL. 
    print $url['scheme'].'://'.$url['host'].'/'.ltrim($relative, '/'); 
} 

看一看到http_build_url方法創建一個絕對定位的另一種方式。

+1

一個親戚也可以是$ relative ='../hello/index.php'; – Francesco 2012-02-12 23:10:19