悉远

 找回密码
 注册
搜索
查看: 3001|回复: 0

PHP采集获取指定网址的内容

[复制链接]
发表于 2013-5-22 00:38:31 | 显示全部楼层 |阅读模式
用php来获取指定网页内容的实现代码,一般采集程序经常用的一些代码,这里只是一个简单的基础。更详细的资料可以参考php 采集成品,可以使用的源码,这样才能学会更多的东西。

参考别人想法变成自己的想法,你会发现慢慢下来以后你就拥有了临时解决很多问题的思路与方法。
  1. <?php
  2. /*
  3. 功能:获取页面内容,存储下来阅读; lost63
  4. */
  5. Class GetUrl {
  6.     var $url; //地址
  7.     var $result; //结果
  8.     var $content; //内容
  9.     var $list; //列表
  10.     function GetUrl($url) {
  11.         $this->url = $url;
  12.         $this->GetContent();
  13.         $this->GetList();
  14.         $this->FileSave();
  15.         //print_r($this->list[2]);
  16.         
  17.     }
  18.     private function GetContent() {
  19.         $this->result = fopen($this->url, "r");
  20.         while (!feof($this->result)) {
  21.             $this->content.= fgets($this->result, 9999);
  22.         }
  23.     }
  24.     private function GetList() {
  25.         preg_match_all('/<a(.*?)href="(.*?)">(.*?)<\/a>/', $this->content, $this->list);
  26.         $this->list[2] = array_unique($this->list[2]); //移除相同的值
  27.         while (list($key, $value) = each($this->list[2])) {
  28.             if (strpos($value, ".html") == 0 || strpos($value, "jiaocheng") == 0) {
  29.                 unset($this->list[2][$key]);
  30.             } else {
  31.                 $this->list[2][$key] = substr($value, 0, strpos($value, ".html")) . ".html"; //去掉不需要的标签
  32.                
  33.             }
  34.         }
  35.     }
  36.     private function FileSave() {
  37.         foreach ($this->list[2] as $value) {
  38.             $this->url = $value; //重新赋值
  39.             $this->content = null;
  40.             $this->GetContent(); //提取内容
  41.             preg_match_all('/<title>(.*?)<\/title>/', $this->content, $files); //取标题
  42.             $filename = $files[1][0] . ".html"; //存储名
  43.             $content = $this->str_cut($this->content, 'http://pagead2.googlesyndication.com/pagead/show_ads.js', '<div id="article_detail">');
  44.             $file = fopen($filename, "w");
  45.             fwrite($file, $content);
  46.             fclose($file);
  47.             echo $filename . "保存 OK<br>\n";
  48.         }
  49.     }
  50.     function str_cut($str, $start, $end) {
  51.         $content = strstr($str, $start);
  52.         $content = substr($content, strlen($start) , strpos($content, $end) - strlen($start));
  53.         return $content;
  54.     }
  55. }
  56. $w = new GetUrl("http://www.myolnet.com/forum.php?mod=forumdisplay&fid=45");
  57. ?>
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|QQ客服|联系我们|Archiver|手机版|小黑屋|悉远网络 ( 鄂ICP备09013446号 )

GMT+8, 2024-4-24 01:01 , Processed in 0.038762 second(s), 7 queries , Redis On.

Powered by Discuz! X3.5

Copyright © 2001-2023 Tencent Cloud.

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