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

您也可以通过以下方式执行此操作:

<?php
$url = "http://www.example.com";
$headers = [
'Content-Type: application/json',
'Authorization: Token YOUR_Session_TOKEN'
];
$post_data = [
'app_ids' => [
"com.exmaple.app"
],
'data' => [
'title' => 'Title', 
'content' => 'Content'
],
];
$post_data = json_encode($post_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
// For debugging
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($response);

最新更新