php - PHP 运行 curl 命令
问题描述
我有这个卷曲代码
curl -X POST https://url.com -H 'authorization: Token YOUR_Session_TOKEN' -H 'content-type: application/json' -d '{"app_ids":["com.exmaple.app"], "data" : {"title":"Title", "content":"Content"}}
用于从 Web 服务向移动应用程序推送通知。如何在 PHP 中使用此代码?我无法理解 -H 和 -d 标签
解决方案
您可以使用此网站转换任何此类: https ://incarnate.github.io/curl-to-php/
但基本上d
是有效载荷(您随请求发送的数据:通常是 POST 或 PUT);H
代表标题:每个条目都是另一个标题。
所以最一对一的例子是:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://url.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"app_ids\":[\"com.exmaple.app\"], \"data\" : {\"title\":\"Title\", \"content\":\"Content\"}}");
$headers = array();
$headers[] = 'Authorization: Token YOUR_Session_TOKEN';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
但是您可以通过首先创建具有属性的数组然后对其进行编码来使其更加动态和易于操作基于 PHP 的变量:
$ch = curl_init();
$data = [
'app_ids' => [
'com.example.app'
],
'data' => [
'title' => 'Title',
'content' => 'Content'
]
];
curl_setopt($ch, CURLOPT_URL, 'https://url.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$headers = array();
$headers[] = 'Authorization: Token YOUR_Session_TOKEN';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
我建议阅读 php-curl 的手册: https ://www.php.net/manual/en/book.curl.php
推荐阅读
- ansible - 我应该为简单的单节点 MongoDB 实例使用什么 Ansible Galaxy 角色
- php - 如何解决此错误“您的要求无法解析为可安装的软件包集”
- java - 我想创建一个文件并存储在下面的 HTTPS 路径中,该文件适用于本地存储,您能帮我了解如何存储文件 http 路径吗?
- sql - 如何在 SQL 中对 COUNT 列表求和
- javascript - Javascript:速率限制,但超过限制时继续执行
- reactjs - React 导航 v5 + firebase 身份验证
- javascript - 用 ejs 的客户端 javascript 文件表达
- java - 如何连接Mysql ussign Intellij Idea
- java - Spring Data(Hibernate)动态 WHERE 子句
- kubernetes - Helm 与 Terraform