php - 使用 php 访问 json api

标签 php api curl

我正在尝试学习如何与 json api 交互。 在文档中,他们给了我一个curl示例:

如果我将其作为命令运行,它会正常工作,以 json 格式提供我的数据。

我认为我走在正确的轨道上:PHP + curl, HTTP POST sample code?

但显然不是,因为我不知道如何处理该命令的 -H 部分。

curl -H "APIKey:My:ApI;key;" -H "Content-Type:.../json" "https://urlofapp.com/API/GetTransaction" -d "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}" > test.json

尝试将结果放入一个数组中,我可以对其求和并显示他们今年的订单总数。

从我上面提供的链接中,我试图以此开始:

// set post fields
$post = [
'CustomerID' => 12345,
'StartDate' => 2018-01-01,
'EndDate'   => 2018-12-31,
];

$ch = curl_init('https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

// execute!
$response = curl_exec($ch);

// close the connection, release resources used
curl_close($ch);

// do anything you want with your response
var_dump($response);

最佳答案

-h 命令引用 header 。

尝试下面的代码,

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Apikey: My:ApI;key;';
$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);

我用下面的方法将curl命令转换为PHP脚本,

https://incarnate.github.io/curl-to-php/

希望它会有用。

关于php - 使用 php 访问 json api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54264324/

相关文章:

PHP :Why PHP-Curl is not working with nginx

javascript - 将 <script> 标签中的网站页面源数据存储到数据库 (php)

php - 如何在 PHP GET URL 变量(或函数参数)中使用&符号?

php - 我的 AJAX 表单不会提交并返回响应

azure - API 连接 - ARM 模板中的用户名和密码

java - Android Studio 解析 JSON 对象的方法

php - 如何从 mySQL 中选择 256 位加盐和加密值

php - Docker上的Symfony4 Uncaught BadRequestHttpException

database - 在 Perl 中创建公共(public)访问 API

javascript - 将 CURL 命令转换为 NPM 请求调用