以下は、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:\WINDOWS\system32にコピーする必要があります。Linuxではcurl拡張機能をインストールします。