這篇文章主要介紹了PHP中4種常用的抓取網(wǎng)絡(luò)數(shù)據(jù)方法,本文講解使用file_get_contents函數(shù)、fopen函數(shù)、curl庫(kù)三種常見(jiàn)方法抓取網(wǎng)絡(luò)數(shù)據(jù),并給出了代碼實(shí)例,需要的朋友可以參考下
本小節(jié)的名稱(chēng)為 fsockopen,curl與file_get_contents,具體是探討這三種方式進(jìn)行網(wǎng)絡(luò)數(shù)據(jù)輸入輸出的一些匯總。關(guān)于 fsockopen 前面已經(jīng)談了不少,下面開(kāi)始轉(zhuǎn)入其它。這里先簡(jiǎn)單羅列一下一些常見(jià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打開(kāi)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'=>'m.survivalescaperooms.com',
- '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庫(kù),使用curl庫(kù)之前,可能需要查看一下php.ini是否已經(jīng)打開(kāi)了curl擴(kuò)展
- $url = 'http://localhost/test2.php?site=vevb.com';
- $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;
新聞熱點(diǎn)
疑難解答