博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP几种抓取网络数据的常见方法
阅读量:4606 次
发布时间:2019-06-09

本文共 1369 字,大约阅读时间需要 4 分钟。

//本小节的名称为 fsockopen,curl与file_get_contents,具体是探讨这三种方式进行网络数据输入输出的一些汇总。关于 fsockopen 前面已经谈了不少,下面开始转入其它。这里先简单罗列一下一些常见的抓取网络数据的一些方法。

//1. 用 file_get_contents 以 get 方式获取内容:
$url = 'http://localhost/test2.php';
$html = file_get_contents($url);
echo $html;

//2. 用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);

//3. 用file_get_contents函数,以post方式获取url

$data = array(

 'foo'=>'bar',
 'baz'=>'boom',
 'site'=>'www.nowamagic.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 = "";

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;

//4、使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展

$url = 'http://localhost/test2.php?site=nowamagic.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;

转载于:https://www.cnblogs.com/gide/p/4551098.html

你可能感兴趣的文章
WCF 中,出现The remote server returned an unexpected response: (400) Bad Request.
查看>>
缓存概要
查看>>
vue项目中使用百度地图的方法
查看>>
[Vue-rx] Stream an API using RxJS into a Vue.js Template
查看>>
[Javascript] lodash: memoize() to improve the profermence
查看>>
手写符合Promise/A+规范的Promise
查看>>
Python time和datetime模块
查看>>
JPA、JTA、XA相关索引
查看>>
查询语句的练习
查看>>
Java EE的map
查看>>
webdriver.py--解说
查看>>
windows 下配置Eclipse che
查看>>
SearchSploit
查看>>
关于C语言中的转义字符
查看>>
用正则表达式从网页里面提取视频地址
查看>>
JAVA线程优先级
查看>>
解决VC几个编译问题的方法——好用
查看>>
SPOJ #11 Factorial
查看>>
City Upgrades
查看>>
order set 有序集合
查看>>