The following are several commonly used methods of using php to crawl the content of web pages.
1. file_get_contents
PHP code
The code is as follows:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?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 code
The code is as follows:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?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 code
The code is as follows:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?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;
?>
Note:
1. Use file_get_contents and fopen to enable allow_url_fopen.
Method: Edit php.ini and set allow_url_fopen = On. When allow_url_fopen is turned off, neither fopen nor file_get_contents can open remote files.
2. To use curl, you must have space to enable curl.
Method: Modify php.ini under Windows, remove the semicolon in front of extension=php_curl.dll, and copy ssleay32.dll and libeay32.dll to C:WINDOWSsystem32; install the curl extension under Linux.