1. 程式人生 > >使用php獲取網頁內容

使用php獲取網頁內容

1。使用xmlhttp物件,類似於asp中的ActiveXObject物件,其實xmlhttp無非就是get和put的操作,在php裡面

get的,直接用file_get_contents/fopen/readfile這些函式就是了

put的,自己寫fsockopen傳送也行,用NET_Curl也行

(直接用系統函式要簡單,通用,耗費資源少)

$xhr = new COM("MSXML2.XMLHTTP");
$xhr->open("GET","http://localhost/xxx.php?id=2",false);
$xhr->send();
echo $xhr->responseText

2。上面說的file_get_contents實現

<?php

$url = "http://www.jb51.net";
$contents = file_get_contents($url);

//如果出現中文亂碼使用下面程式碼
//$getcontent = iconv("gb2312", "utf-8",$contents);
echo $contents;
?>

3.fopen->fread->fclose
PHP程式碼
[複製此程式碼]CODE:
<?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;
?>

4.curl
PHP程式碼
[複製此程式碼]CODE:
<?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;
?>

注:
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擴充套件。