php语言 百分网手机站

php抓取页面的的方法

时间:2020-09-02 19:34:25 php语言 我要投稿

php抓取页面的的方法

  导语:抓取和分析一个文件是非常简单的事。下面是php抓取页面的`的方法,希望对你有所帮助:

  一、 PHP抓取页面的主要方法:

  1. file()函数

  2. file_get_contents()函数

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

  4.curl方式

  5. fsockopen()函数 socket模式

  6. 使用插件

  二、PHP解析html或xml代码主要方式:

  1. file()函数

  $url='http://t.qq.com';

  $lines_array=file($url);

  $lines_string=implode('',$lines_array);

  echo htmlspecialchars($lines_string);

  2. file_get_contents()函数

  使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置 allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。

  $url='http://t.qq.com';

  $lines_string=file_get_contents($url);

  echo htmlspecialchars($lines_string);

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

  $url='http://t.qq.com';

  $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扩展。

  $url='http://t.qq.com';

  $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测试一下了。

  $fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);

  if (!$fp) {

  echo "ERROR: $errno - $errstr
"

  } else {

  fwrite($fp, " ")

  echo fread($fp, 26)

  fclose($fp)

  }


【php抓取页面的的方法】相关文章:

php抓取页面的方法09-23

php抓取页面的几种方法09-10

php技术生成静态页面的方法08-15

PHP页面跳转到另一个页面的方法09-22

PHP伪静态的方法09-28

高效学习PHP的方法08-22

PHP获取星期的方法08-16

php变量定义方法09-14

PHP 表单验证方法09-12