php利用fopen實現簡單的網頁採集程式

來源:互聯網
上載者:User
 代碼如下 複製代碼


/**
* 根據URL採集網頁內容
*
* @param string $url 連結地址
* @return string
*/

private function fetchbyurl($url){
$handle = fopen($url, ‘r’);
$content = ”;
while (!feof($handle)){
$content .= fgets($handle, 10000);
}
return $content;
//?$this->utf8_iconv($content):”;
}

/*擷取所有匹配的內容
* @param string $str 內容
* @param string $start 起始匹配
* @param string $end 中止匹配
* @return array
*/

private function utf8_iconv($content){
return iconv(‘GBK’, ‘UTF-8′, $content);
}
private function strCutAll($str,$start,$end){
$content = explode($start,$str);
$matchs = array();
$sum = count($content);
for( $i = 1;$i < $sum;$i++ ){
$tmp = explode($end,$content[$i]);
$matchs[] = $tmp[0];
unset($tmp);
}
return $matchs;
}

/*擷取第一個匹配的內容
* @param string $str 內容
* @param string $start 起始匹配
* @param string $end 中止匹配
* @return string
*/
private function strCut($str, $start, $end){
$content = strstr( $str, $start );
$content = substr( $content, strlen( $start ), strpos( $content, $end ) - strlen( $start ) );
return $content;
}

測試:

/*採集程式*/header("content-Type: text/html; charset=utf-8"); //$nr = file_get_contents(‘/webback/php/php-yi-ju-hua-hou-men-zhuan’); $nr = $this->fetchbyurl(‘/webback/php/php-yi-ju-hua-hou-men-zhuan’);//推薦,還可以用curl dump($this->strCut($nr,’<div class="context">’,'<div class="betterrelated">’));//得到內容。需要進一步過濾用(preg_match_all) dump($this->strCutAll($nr,’<title>’,'</title>’)); 得到標題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.