PHP中使用cURL实现Get和Post请求的方法
时间:2023-08-18 13:15:35
1.cURL介绍
cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 库。本文将介绍 cURL 的一些高级特性,以及在PHP中如何运用它。
2.基本结构
在学习更为复杂的功能之前,先来看一下在PHP中建立cURL请求的基本步骤:
(1)初始化
curl_init()
(2)设置变量
curl_setopt() 。最为重要,一切玄妙均在此。有一长串cURL参数可供设置,它们能指定URL请求的各个细节。要一次性全部看完并理解可能比较困难,所以今天我们只试一下那些更常用也更有用的选项。
(3)执行并获取结果
curl_exec()
(4)释放cURL句柄
curl_close()
3.cURL实现Get和Post
3.1 Get方式实现
//初始化
$ch = curl_init();
//设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, "https://www.aspxhome.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//执行并获取HTML文档内容
$output = curl_exec($ch);
//释放curl句柄
curl_close($ch);
//打印获得的数据
print_r($output);
3.2 Post方式实现
$url = "http://localhost/web_services.php";
$post_data = array ("username" => "bob","key" => "12345");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post数据
curl_setopt($ch, CURLOPT_POST, 1);
// post的变量
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
//打印获得的数据
print_r($output);
以上方式获取到的数据是json格式的,使用json_decode函数解释成数组。
$output_array = json_decode($output,true);
如果使用json_decode($output)解析的话,将会得到object类型的数据。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python内置函数——__import__ 的使用方法
![](https://img.aspxhome.com/file/2023/6/95826_0s.jpg)
解决Mac下首次安装pycharm无project interpreter的问题
python实现简单神经网络算法
![](https://img.aspxhome.com/file/2023/9/97549_0s.jpg)
浅析Python 抽象工厂模式的优缺点
![](https://img.aspxhome.com/file/2023/1/90431_0s.png)
Bootstrap4如何定制自己的颜色和风格
![](https://img.aspxhome.com/file/2023/0/125930_0s.png)
推荐19个很有用的 JavaScript 库
JavaScript简单实现弹出拖拽窗口(一)
![](https://img.aspxhome.com/file/2023/6/132816_0s.gif)
asp按关键字查询XML的代码
基于python实现判断字符串是否数字算法
![](https://img.aspxhome.com/file/2023/1/83831_0s.png)
基于laravel缓冲cache的用法详解
小白学Python之实现OCR识别
![](https://img.aspxhome.com/file/2023/6/80476_0s.jpg)
Python爬虫设置代理IP的方法(爬虫技巧)
PHP get_html_translation_table()函数用法讲解
![](https://img.aspxhome.com/file/2023/7/55387_0s.png)
在ASP.NET 2.0中操作数据之五十六:使用ObjectDataSource缓存数据
![](https://img.aspxhome.com/file/2023/5/126205_0s.png)
Python源码学习之PyObject和PyTypeObject
![](https://img.aspxhome.com/file/2023/2/62252_0s.png)
Go 微服务开发框架DMicro设计思路详解
![](https://img.aspxhome.com/file/2023/8/125088_0s.png)
分布式爬虫scrapy-redis的实战踩坑记录
![](https://img.aspxhome.com/file/2023/9/120969_0s.png)