2010-07-01 68 views
1

我的拼貼項目最近兩天被擊中 我有代碼提取鏈接,但我也需要鏈接標籤。我需要將鏈接存儲在數組中,並將鏈接標籤存儲在另一個數組中。 例如,如果網站bbc.com有代碼運動,我需要$ linklabel [0] = sports和$ link [0] = bbc.com/sports.html。php curl,鏈接標籤提取

該代碼是下面,但是會出現誤差爲致命錯誤:調用未定義方法DOMXPath ::找到()在C:?線14上

] *> \瓦帕\萬維網\測試\ d.php。 ?* @ SI'); //刪除javascript $ var = preg_replace($ search,「\ n」,html_entity_decode($ var)); //去掉javascript $ linklabel = array(); $ link = array(); $ dom = new DOMDocument($ var); @ $ dom-> loadHTML($ var); $ xpath = new DOMXPath($ dom); //獲取DOM節點 foreach($ xpath-> find('a')as $ element) array_push($ linklabel,$ element-> innerText); print $ linklabel; array_push($ link,$ element-> href); print $ link。'
'; } 功能fread_url($ URL) { 如果(function_exists( 「curl_init」)){$ CH = curl_init(); $ user_agent =「Mozilla/4.0(compatible; MSIE 5.01;」。 「Windows NT 5.0)」; $ ch = curl_init(); curl_setopt($ ch,CURLOPT_USERAGENT,$ user_agent); curl_setopt($ ch,CURLOPT_HTTPGET,1); curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,1); curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,1); curl_setopt($ ch,CURLOPT_URL,$ url); curl_setopt($ ch,CURLOPT_COOKIEJAR,'cookie.txt'); $ html = curl_exec($ ch); //打印$ html; //打印網頁。 curl_close($ ch); } else { $ hfile = fopen($ url,「r」);如果($ hfile){(!feof($ hfile)){hffile} {ffile($ hfile,1024); } } } return $ html; } ?>
+0

刪除請求通過電子郵件與您聯繫 - 爲了您自己的利益,以防止downvotes。 :) – 2010-07-01 23:50:38

+0

@Pekka,感謝編輯,我自己會這麼做! – 2010-07-01 23:51:47

回答

1

這是很容易使用Simple HTML DOM.

$html = file_get_html('http://www.google.com/'); 

$linklabel = array(); 
$link = array(); 

foreach($html->find('a') as $element) 
    { 
    array_push($linklabel, $element->innerText); 
    array_push($link, $element->href); 
    } 
+0

+1因爲你真的需要代表。這也是正確的答案:D但 - >標籤不會給出超鏈接的文本,它會返回標籤屬性.... – 2010-07-01 23:52:23

+0

@Byron你是對的,謝謝,更正! – Unicron 2010-07-01 23:55:08

+0

什麼是$元素在這裏。我得到和函數find('a')的錯誤。如果你能解釋一點,這將是gr8幫助 – 2010-07-02 02:03:49

0

你來對地方了。請刪除您的電子郵件,因爲這是一個共享的社區資源,而不是您的個人Q/A機器。

所以你應該使用simple_html_dom解析鏈接。然後它變得如此簡單

$dom = file_get_html('http://www.google.com/'); 

// get the label of all links. see the docs for searching options 
foreach ($dom->find('a') as $links) 
{ 
    $link->innerText; 
    $link->href; 
}