加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php里fsockopen采集网页内容实例

发布时间:2022-02-14 13:41:34 所属栏目:PHP教程 来源:互联网
导读:fsockopen是php中一个比较实用的函数了,下面我来介绍利用fsockopen函数来采集网页的程序. 用法:int fsockopen(string hostname,int port,int [errno],string [errstr],int [timeout]); 一个采集网页实例,代码如下: ?php function get_url ($url,$cookie=fa
  fsockopen是php中一个比较实用的函数了,下面我来介绍利用fsockopen函数来采集网页的程序.
 
  用法:int fsockopen(string hostname,int port,int [errno],string [errstr],int [timeout]);
 
  一个采集网页实例,代码如下:
 
  <?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)//开源代码Cuoxin.com
  {
  $body= stristr($rowdata,”rnrn”);
  $body=substr($body,4,strlen($body));
  return $body;
  }
  
      return false;
  }
  ?>
  被禁用后的解决方法:
 
  服务器同时禁用了fsockopen pfsockopen,那么用其他函数代替,如stream_socket_client(),注意:stream_socket_client()和fsockopen()的参数不同.
 
  fsockopen:替换为 stream_socket_client,然后,将原fsockopen函数中的端口参数“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_timeo

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读