PHP網頁抓取

來源:互聯網
上載者:User

用php抓取頁面的內容在實際的開發當中是非常有用的,如作一個簡單的內容採集器,提取網頁中的部分內容等等,抓取到的內容在通過Regex做一下過濾就得到了你想要的內容,至於如何用Regex過濾,在這裡就不做介紹了,有興趣的同學可以參考本站的《Regex》板塊:http://phpzixue.cn/articles11.shtml,以下就是幾種常用的用php抓取網頁中的內容的方法。
1.file_get_contents
PHP代碼

<?php    
$url = "http://www.phpzixue.cn";
$contents = file_get_contents($url);
//如果出現中文亂碼使用下面代碼
//$getcontent = iconv("gb2312", "utf-8",$contents);  
echo $contents;
?>   

2.curl
PHP代碼

<?php    
$url = "http://www.phpzixue.cn";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//在需要使用者檢測的網頁裡需要增加下面兩行
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>

3.fopen->fread->fclose
PHP代碼

<?php    
$handle = fopen ("http://www.phpzixue.cn", "rb");
$contents = "";
do {
    $data = fread($handle, 1024);
    if (strlen($data) == 0) {
    break;
    }
    $contents .= $data;
} while(true);
fclose ($handle);
echo $contents;
?>

註:
1.使用file_get_contents和fopen必須空間開啟allow_url_fopen。方法:編輯php.ini,設定 allow_url_fopen = On,allow_url_fopen關閉時fopen和file_get_contents都不能開啟遠程檔案。
2.使用curl必須空間開啟curl。方法:windows下修改php.ini,將extension=php_curl.dll前面的分號去掉,而且需要拷貝ssleay32.dll和libeay32.dll到C:/WINDOWS/system32下;Linux下要安裝curl擴充。

 

 

another

前些日子跟別的公司合作了一個簡訊投票業務,對方需要把使用者上行發送到我們平台,我這需要receive他的資料,然後他需要每發送一個資料我這邊判斷正確的話就輸出一個內容讓其抓取。之前只做過接收資料並處理,至於抓取沒做過。在網上找了好多關於相關的文檔。不過感覺都挺麻煩,最後就直接刪除了很多功能代碼,不過可以完成自己需要的功能了!
我說下我做的幾個簡單步驟:
       1.可以建立一個test頁面,如test.php
<html>
<head>
   <title>PHP 網頁抓取測試</title>
</head>
<body   >
<?php echo '<p>Hello World!</p>'; ?>
</body>
</html>
    
     2.建立抓取頁面,如zhuaqu.php,代碼如下:
<html>
<head>
<title>實用抓取網頁內容測試 </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body   >
<?php
$url = 'http://localhost/test.php'; //測試本地網頁
#$url = 'http://www.myenjoylife.cn/index.php'; //抓取www.myenjoylife.cn首頁內容
$lines_array = file($url);
$lines_string = implode('', $lines_array);
eregi("(.*)", $lines_string, $head);
echo $head[0];
?>
</body>
</html>
3. 完成,就這麼簡單,如果你想抓取別的網頁內容,只要改$url參數變數值就OK啦!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.