php - 使用 php 访问 json api
问题描述
我正在尝试学习如何与 json api 交互。在文档中,他们给了我一个 curl 示例:
如果我将其作为命令运行,它可以正常工作,以 json 格式提供我的数据。
我以为我在正确的轨道上:PHP + curl, HTTP POST 示例代码?
但显然不是因为我不知道如何处理该命令的 -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 命令引用标题。
试试下面的代码,
// 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/
希望它会有用。
推荐阅读
- dart - 用颤振绘制虚线弧
- swift - 我有一个“UIImage”,我想将其转换为 NSData 以上传到 firebase 存储
- amazon-web-services - AWS Cloudfront CacheBehavior 的 PathPattern 中可接受的通配符
- c - 在从标准输入读取的while循环中捕获EOF字符
- python-3.x - 有没有办法让 Splash 等到站点上的所有 java 脚本加载?
- c++ - 修改内存区域 - 返回 0xCC VC++
- c - 执行 make 时出错:mingw32-make: *** No rule to make target
- java - “请求的资源不支持 http 方法 'GET'” - 但我没有使用 C# 或 asp.net,我是发出请求的人
- r - 编写循环以一次在多个列表上执行
- reactjs - React 应用程序未登录到控制台或终端窗口