程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> php獲取網頁內容方法總結

php獲取網頁內容方法總結

編輯:PHP綜合
抓取到的內容在通過正則表達式做一下過濾就得到了你想要的內容,至於如何用正則表達式過濾,在這裡就不做介紹了,有興趣的,以下就是幾種常用的用php抓取網頁中的內容的方法。
1.file_get_contents
PHP代碼
復制代碼 代碼如下:
<?php
$url = "http://www.jb51.net";
$contents = file_get_contents($url);
//如果出現中文亂碼使用下面代碼
//$getcontent = iconv("gb2312", "utf-8",$contents);
echo $contents;
?>

2.curl
PHP代碼
復制代碼 代碼如下:
<?php
$url = "http://www.jb51.net";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//在需要用戶檢測的網頁裡需要增加下面兩行
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>

3.fopen->fread->fclose
PHP代碼
復制代碼 代碼如下:
<?php
$handle = fopen ("http://www.jb51.net", "rb");
$contents = "";
do {
$data = fread($handle, 1024);
if (strlen($data) == 0) {
break;
}
$contents .= $data;
} while(true);
fclose ($handle);
echo $contents;
?>

注:
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擴展。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved