我正在尝试学习如何与 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/