以下就是幾種常用的用php抓取網頁中的內容的方法。
1. file_get_contents
PHP代碼
代碼如下:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?php
header("Content-Type:text/html;charset=utf-8");
$keyworld="煤層";
$keyworld=iconv("utf-8","gb2312",$keyworld);
$url = "http://www.baidu.com/s?f=8&wd=$keyworld";
$html = file_get_contents($url);
//如果出現中文亂碼使用下面代碼
//$html = iconv("gb2312", "utf-8//IGNORE",$html);
$str = array('音樂'=>'MUSIC');
$str += array('新聞'=> 'NEWS');
$html = strtr($html,$str);
echo $html;
?>2.curl
PHP代碼
代碼如下:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?php
$url = "http://www.baidu.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.baidu.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:WINDOWSsystem32下;Linux下要安裝curl擴展。