Discuz教程网

php抓取网页内容方法总结

[复制链接]
authicon dly 发表于 2011-1-11 19:11:31 | 显示全部楼层 |阅读模式
用php抓取页面的内容在实际的开发当中是非常有用的,如作一个简单的内容采集器,提取网页中的部分内容等等,抓取到的内容在通过正则表达式做一下过滤就得到了你想要的内容,至于如何用正则表达式过滤,在这里就不做介绍了,有兴趣的同学可以在本站搜索“正则表达式”,以下就是几种常用的用php抓取网页中的内容的方法。
1.file_get_contents
PHP代码
  1. <?php     
  2. $url = "http://www.phpzixue.cn";  
  3. $contents = file_get_contents($url);  
  4. //如果出现中文乱码使用下面代码  
  5. //$getcontent = iconv("gb2312", "utf-8",$contents);   
  6. echo $contents;  
  7. ?>
复制代码

   

2.curl
PHP代码
  1. <?php     
  2. $url = "http://www.phpzixue.cn";  
  3. $ch = curl_init();  
  4. $timeout = 5;  
  5. curl_setopt($ch, CURLOPT_URL, $url);  
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
  7. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
  8. //在需要用户检测的网页里需要增加下面两行  
  9. //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);  
  10. //curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);  
  11. $contents = curl_exec($ch);  
  12. curl_close($ch);  
  13. echo $contents;  
  14. ?>  
复制代码


3.fopen->fread->fclose
PHP代码
  1. <?php     
  2. $handle = fopen ("http://www.phpzixue.cn", "rb");  
  3. $contents = "";  
  4. do {  
  5.    $data = fread($handle, 1024);  
  6.    if (strlen($data) == 0) {  
  7.    break;  
  8.    }  
  9.    $contents .= $data;  
  10. } while(true);  
  11. fclose ($handle);  
  12. echo $contents;  
  13. ?>
复制代码


注:
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扩展。







上一篇:PHP编程中常用到的MYSQL数据类型摘录
下一篇:smarty的预保留变量总结
authicon D_hong 发表于 2011-6-19 09:59:52 | 显示全部楼层
这个贴不错!!!
authicon haidideyu 发表于 2011-6-20 00:00:06 | 显示全部楼层
顶你一下,好贴要顶!
authicon 咫尺天 发表于 2011-6-22 07:59:58 | 显示全部楼层
回贴下载呀
authicon mjz 发表于 2011-6-23 12:02:00 | 显示全部楼层
支持楼主,顶一下
authicon 暗夜的烟火 发表于 2011-6-23 12:59:40 | 显示全部楼层
真的有意思!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-11 03:25

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表