2010-07-01 70 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; 
}