PHP网络数据抓取方法概述
本节主要围绕 fsockopen、cURL 以及 file_get_contents 展开,旨在总结利用这些手段进行网络数据输入输出的相关实践。鉴于前文已对 fsockopen 进行了较为详尽的阐述,此处将重点转向其他技术。首先简要梳理一下常见的网络数据抓取方案。
第一种方法:利用 file_get_contents 函数以 GET 方式获取目标内容。
$url = 'http://localhost/test2.php';
$html = file_get_contents($url);
echo $html;
第二种方法:通过 fopen 打开 URL,并以 GET 方式提取内容。
$url = 'http://localhost/test2.php';
$fp = fopen($url, 'r');
stream_get_meta_data($fp);
$result = '';
while(!feof($fp))
{
$result .= fgets($fp, 1024);
}
echo "url body: $result";
fclose($fp);
第三种方法:使用 file_get_contents 函数,配合 stream context 以 POST 方式向 URL 提交数据并获取响应。
$data = array(
'foo'=>'bar',
'baz'=>'boom',
'site'=>'www.jb51.net',
'name'=>'nowa magic');
$data = http_build_query($data);
//$postdata = http_build_query($data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $data
//'timeout' => 60 * 60 // 超时时间(单位:s)
)
);
$url = "http://localhost/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
第四种方法:调用 cURL 库。在使用该库之前,需确认 php.ini 配置文件中是否已启用 curl 扩展。
$url = 'http://localhost/test2.php?site=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);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;