php file_get_contents數據采集與常用見問題解決
來源:程序員人生 發布時間:2013-11-07 12:33:37 閱讀次數:4768次
在批量的數據采集在php中很少會使用file_get_contents函數來操作,但是如果是小量的我們可以使用file_get_contents函數操作,因為它不但好用而且簡單易學,下面我來介紹file_get_contents用法與使用過程中的問題解決辦法。
先來看問題,file_get_contents不能獲取帶端口的網址,例如如下代碼:
file_get_contents('http://localhost:12345');
沒有任何獲取,解決方法是:關閉selinux
1 永久方法 – 需要重啟服務器
修改/etc/selinux/config文件中設置SELINUX=disabled ,然后重啟服務器。
2 臨時方法 – 設置系統參數
使用命令setenforce 0附:
setenforce 1 設置SELinux 成為enforcing模式
setenforce 0 設置SELinux 成為permissive模式
file_get_contents超時,代碼如下:
- function _file_get_contents($url)
- {
- $context = stream_context_create(array(
- 'http' => array(
- 'timeout' => 180
- )
- ));
- return @file_get_contents($url, 0, $context);
- }
好了上面的問題得到解決之后我們可以開始采集了,代碼如下:
- <?php
-
- if (!strpos($_SERVER["REQUEST_URI"],".html"))
- {
- $page="http://qq.ip138.com/weather/";
- $html = file_get_contents($page,'r');
- $pattern="/<B>全國主要城市、縣當天和未來五天天氣趨勢預報在線查詢</B>(.*?)<center style="padding:3px">/si";
-
- preg_match($pattern,$html,$pg);
- echo "";
-
- $p=preg_replace('//weather/(w+)/index.htm/', 'tq.php/$1.html', $pg[1]);
- echo $p;
- }
-
- else if(!strpos($_SERVER["REQUEST_URI"],"?")){
-
- $province=explode("/",$_SERVER["REQUEST_URI"]);
- $province=explode(".",$province[count($province)-1]);
- $province=$province[0];
-
-
-
- $page="http://qq.ip138.com/weather/".$province."/index.htm";
-
- if (!@fopen($page, "r")) {
- die("對不起,該地址不存在!<a href=javascript:history.back(1)>點擊這里返回</a>");
- exit(0);
- }
- $html = file_get_contents($page,'r');
- $pattern="/五天天氣趨勢預報</B>(.*?)請輸入輸入市/si";
- preg_match($pattern,$html,$pg);
- echo "";
-
- $p=preg_replace('//weather/(w+)/(w+).htm/', '$2.html?pro=$1', $pg[1]);
- echo $p;
- }
- else {
-
- $pro=$_REQUEST['pro'];
- $city=explode("/",$_SERVER["REQUEST_URI"]);
- $city=explode(".",$city[count($city)-1]);
- $city=$city[0];
-
-
- $page="http://qq.ip138.com/weather/".$pro."/".$city.".htm";
- if (!@fopen($page, "r")) {
- die("對不起,該地址不存在!<a href=javascript:history.back(1)>點擊這里返回</a>");
- exit(0);
- }
- $html = file_get_contents($page,'r');
- $pattern="/五天天氣趨勢預報</B>(.*?)請輸入輸入市/si";
- preg_match($pattern,$html,$pg);
- echo "";
-
- $p=preg_replace('//image//', 'http://qq.ip138.com/image/', $pg[1]);
- echo $p;
- }
- ?>
如果上面辦法無法采集到數據我們可以使用以下代碼來處理,代碼如下:
- <?php
- $url = "http://www.phpfensi.com";
- $ch = curl_init();
- $timeout = 5;
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
-
-
-
- $contents = curl_exec($ch);
- curl_close($ch);
- echo $contents;
- ?>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈