PHP獲取網頁內容的幾種方法

2022-03-19 19:56:45 字數 2548 閱讀 3605

方法1: 用file_get_contents以get方式獲取內容

<?php

$url='';

$html= file_get_contents($url);

echo$html;

?>

方法2:用file_get_contents函式,以post方式獲取url

如果需要再傳遞cookie資料,則把

"content-length: " . strlen($data) . "\r\n",

修改為 "content-length: " . strlen($data) . "\r\n".

"cookie:cookie1=c1;cookie2=c2\r\n";即可

方法3: 用fopen開啟url, 以get方式獲取內容

<?php

$fp= fopen($url,'r');

$header= stream_get_meta_data($fp);//獲取報頭資訊

while(!feof($fp))

echo"url header:

":echo"url body: $result";

fclose($fp);

?>

方法4: 用fopen開啟url, 以post方式獲取內容

方法5:用fsockopen函式開啟url,以get方式獲取完整的資料,包括header和body

<?php

functionget_url ($url,$cookie=false)

else

fclose($fp);

return$result;}}

//獲取url的html部分,去掉header

functiongeturlhtml($url,$cookie=false)

returnfalse;

}?>

方法6:用fsockopen函式開啟url,以post方式獲取完整的資料,包括header和body

方法7:使用curl庫,使用curl庫之前,可能需要檢視一下php.ini是否已經開啟了curl擴充套件

<?php

$ch= curl_init();

$timeout= 5;

curl_setopt ($ch, curlopt_url, '');

curl_setopt ($ch, curlopt_returntransfer, 1);

curl_setopt ($ch, curlopt_connecttimeout, $timeout);

$file_contents= curl_exec($ch);

curl_close($ch);

echo$file_contents;

?>

這裡收集了3種利用php獲得網頁源**抓取網頁內容的方法,我們可以根據實際需要選用。

1、使用file_get_contents獲得網頁源**

這個方法最常用,只需要兩行**即可,非常簡單方便。

2、使用fopen獲得網頁源**

這個方法用的人也不少,不過**有點多。

3、使用curl獲得網頁源**

使用curl獲得網頁源**的做法,往往是需要更高要求的人使用,例如當你需要在抓取網頁內容的同時,得到網頁header資訊,還有encoding編碼的使用,useragent的使用等等。

PHP獲取網頁內容的幾種方法

方法1 用file get contents以get方式獲取內容 url html file get contents url echo html 方法2 用file get contents函式,以post方式獲取url 如果需要再傳遞cookie資料,則把 content length strl...

HP獲取網頁內容的幾種方法

方法1 用file get contents 以get方式獲取內容 url html file get contents url echo html 方法2 用file get contents函式,以post方式獲取url 如果需要再傳遞cookie資料,則把 header content len...

php獲取網頁內容方法

1.file get contents url contents file get contents url 如果出現中文亂碼使用下面 getcontent iconv gb2312 utf 8 contents echo contents 2.curl url ch curl init timeo...