2012-03-03 222 views
-1

我的任务是仅解析来自给定URL的单个链接。使用CURL解析单个链接并将其保存在txt文件中

问题是,每次刷新页面时,我都会使用Curl下载目标网站,并使用正则表达式来查找链接。当给定的链接相同时,如何避免再次下载目标网站?

$url = 'http://ruh.kz'; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt ($ch , CURLOPT_USERAGENT , "Mozilla/5.0 "); 
curl_setopt ($ch , CURLOPT_RETURNTRANSFER , 1); 
$content = curl_exec($ch); 
curl_close($ch); 

$link = preg_match_all('/<h3 class="entry"><a href="(.*)">(.*)<\/a><\/h3>/', $content, $matches); 
$link = $matches[1][0]; 
$title = $matches[2][0]; 

输出:

<a href="http://ruh.kz<?php print $link; ?>" target="_blank"><?php print $title; ?></a> 

回答

1

解决这个问题的最简单的解决办法是记住在缓存中的所有解析/加载的URL。这意味着,无论何时处理成功,都将URL存储在会话/ cookie /数据库中(以最好的方式为您提供服务)。

页面刷新首先首先检查这个缓存。如果URL没有存储在那里,那么加载/解析是很好的。

0

您可以使用simple html dom先做一个foreach,然后根据需要解析链接。

require('simple_html_dom.php'); 
    $url = 'http://ruh.kz'; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt ($ch , CURLOPT_USERAGENT , "Mozilla/5.0 "); 
    curl_setopt ($ch , CURLOPT_RETURNTRANSFER , 1); 
    $content = curl_exec($ch); 
    curl_close($ch); 
    $html= str_get_html($content); 
    foreach($html->find('.entry') as $element){ 
     preg_match_all('/<a href="(.*)">(.*)<\/a>/', $element, $matches); 
     $link = $matches[1][0]; 
     $title = $matches[2][0]; 
     echo '<a href="http://ruh.kz'.$link,'" target="_blank">'.$title.'</a><br />'; 
    } 
+0

但是,每次刷新页面时都会启动该功能吗? – Heihachi 2012-03-03 09:22:28

+0

是的,当你刷新页面时,它会捕获链接模拟Mozilla浏览器,所以如果你不需要,你可以将它保存为'txt,html'或'sql data'。 – Giberno 2012-03-03 09:25:57

相关问题