fsockopen是php中一個比較實(shí)用的函數(shù)了,下面我來介紹利用fsockopen函數(shù)來采集網(wǎng)頁的程序.
用法:int fsockopen(string hostname,int port,int [errno],string [errstr],int [timeout]);
一個采集網(wǎng)頁實(shí)例,代碼如下:
- <?php
- function get_url ($url,$cookie=false)
- {
- $url = parse_url($url);
- $query = $url[path].”?”.$url[query];
- echo “Query:”.$query;
- $fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
- if (!$fp) {
- return false;
- } else {
- $request = “GET $query HTTP/1.1rn”;
- $request .= “Host: $url[host]rn”;
- $request .= “Connection: Closern”;
- if($cookie) $request.=”Cookie: $cookien”;
- $request.=”rn”;
- fwrite($fp,$request);
- while(!@feof($fp)) {
- $result .= @fgets($fp, 1024);
- }
- fclose($fp);
- return $result;
- }
- }
- //獲取url的html部分,去掉header
- function GetUrlHTML($url,$cookie=false)
- {
- $rowdata = get_url($url,$cookie);
- if($rowdata)//開源代碼Vevb.com
- {
- $body= stristr($rowdata,”rnrn”);
- $body=substr($body,4,strlen($body));
- return $body;
- }
- return false;
- }
- ?>
被禁用后的解決方法:
服務(wù)器同時禁用了fsockopen pfsockopen,那么用其他函數(shù)代替,如stream_socket_client(),注意:stream_socket_client()和fsockopen()的參數(shù)不同.
fsockopen:替換為 stream_socket_client,然后,將原fsockopen函數(shù)中的端口參數(shù)“80”刪掉,并加到$host.
例,代碼如下:
- $fp = fsockopen($host, 80, $errno, $errstr, 30);
- //或
- $fp = fsockopen($host, $port, $errno, $errstr, $connection_timeout);
- //修改后:
- $fp = stream_socket_client("tcp://".$host."80", $errno, $errstr, 30);
- //或
- $fp = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, $connection_timeout);
新聞熱點(diǎn)
疑難解答