欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP中4種常用的抓取網(wǎng)絡(luò)數(shù)據(jù)方法

 更新時(shí)間:2015年06月04日 10:58:46   投稿:junjie  
這篇文章主要介紹了PHP中4種常用的抓取網(wǎng)絡(luò)數(shù)據(jù)方法,本文講解使用file_get_contents函數(shù)、fopen函數(shù)、curl庫三種常見方法抓取網(wǎng)絡(luò)數(shù)據(jù),并給出了代碼實(shí)例,需要的朋友可以參考下

本小節(jié)的名稱為 fsockopen,curl與file_get_contents,具體是探討這三種方式進(jìn)行網(wǎng)絡(luò)數(shù)據(jù)輸入輸出的一些匯總。關(guān)于 fsockopen 前面已經(jīng)談了不少,下面開始轉(zhuǎn)入其它。這里先簡單羅列一下一些常見的抓取網(wǎng)絡(luò)數(shù)據(jù)的一些方法。

1. 用 file_get_contents 以 get 方式獲取內(nèi)容:

$url = 'http://localhost/test2.php';
$html = file_get_contents($url);
echo $html;

2. 用fopen打開url,以get方式獲取內(nèi)容

$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);

3. 用file_get_contents函數(shù),以post方式獲取url

$data = array(
 'foo'=>'bar',
 'baz'=>'boom',
 'site'=>'www.dbjr.com.cn',
 '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 // 超時(shí)時(shí)間(單位:s)
 )
);

$url = "http://localhost/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;

4、使用curl庫,使用curl庫之前,可能需要查看一下php.ini是否已經(jīng)打開了curl擴(kuò)展

$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;

相關(guān)文章

最新評(píng)論