首页 > 解决方案 > 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 标签

标签: phpcurl

解决方案


您可以使用此网站转换任何此类: 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


推荐阅读