程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php中采集抓取頁面函數詳解

php中采集抓取頁面函數詳解

編輯:關於PHP編程

在php中提供了大量的獲取遠程服務器文件的函數,包括有:file()函數、file_get_contents()函數、fopen()->fread()->fclose()模式、curl方式、fsockopen()函數、socket模式等等,下面我來分別來介紹介紹。

1. file()函數

file() 函數把整個文件讀入一個數組中。

與 file_get_contents() 類似,不同的是 file() 將文件作為一個數組返回。數組中的每個單元都是文件中相應的一行,包括換行符在內。

如果失敗,則返回 false。

 代碼如下 復制代碼


<?php
$url='http://www.bKjia.c0m';
$lines_array=file($url);
$lines_string=implode('',$lines_array);
echo htmlspecialchars($lines_string);

?>

2. file_get_contents()函數


file_get_contents() 函數把整個文件讀入一個字符串中。

和 file() 一樣,不同的是 file_get_contents() 把文件讀入一個字符串。

file_get_contents() 函數是用於將文件的內容讀入到一個字符串中的首選方法。如果操作系統支持,還會使用內存映射技術來增強性能。

 

 代碼如下 復制代碼

<?php
$url='http://www.bKjia.c0m';
$lines_string=file_get_contents($url);
echo htmlspecialchars($lines_string);

?>

使用file_get_contents和fopen必須空間開啟allow_url_fopen。方法:編輯php.ini,設置 allow_url_fopen = On,allow_url_fopen關閉時fopen和file_get_contents都不能打開遠程文件。

3. fopen()->fread()->fclose()模式

 代碼如下 復制代碼

<?php
$url='http://www.bKjia.c0m';
$handle=fopen($url,"rb");
$lines_string="";
do{
    $data=fread($handle,1024);
     if(strlen($data)==0) {
        break;
    }
    $lines_string.=$data;
}while(true);
fclose($handle);
echo htmlspecialchars($lines_string);

4. curl方式

使用curl必須空間開啟curl。方法:windows下修改php.ini,將extension=php_curl.dll前面的分號去掉,而且需 要拷貝ssleay32.dll和libeay32.dll到C:WINDOWSsystem32下;Linux下要安裝curl擴展。

 代碼如下 復制代碼

<?php
$url='http://www.bKjia.c0m';
$ch=curl_init();
$timeout=5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$lines_string=curl_exec($ch);
curl_close($ch);
echo htmlspecialchars($lines_string);


5. fsockopen()函數 socket模式
socket模式能否正確執行,也跟服務器的設置有關系,具體可以通過phpinfo查看服務器開啟了哪些通信協議,比如我的本地php socket沒開啟http,只能使用udp測試一下了。

還有一個以curl_開頭的函數,可以實現很多功能。有時間要好好研究!下面是關於fscokopen的介紹


1.PHP fsockopen函數說明:

Open Internet or Unix domain socket connection(打開套接字鏈接)

Initiates a socket connection to the resource specified by target .

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets() , fgetss() , fwrite() , fclose() , and feof() ).就是返回一個文件句柄

開啟PHP fsockopen這個函數

PHP fsockopen需要 PHP.ini 中 allow_url_fopen 選項開啟。

 代碼如下 復制代碼

<?php
set_time_limit(0);
$fp = fsockopen("www.hzhuti.com", 80, $errno, $errstr, 30);
if (!$fp) {
   echo "$errstr ($errno)<br />n";
} else {
   $out = "POST / HTTP/1.1rn";
   $out .= "Host: www.bKjia.c0mrn";
   $out .= "Connection: Closernrn";
   fwrite($fp, $out);
   while (!feof($fp)) {
       echo fgets($fp, 128);
   }
   fclose($fp);
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved