使用php访问json api

使用php访问json api,php,api,curl,Php,Api,Curl,我正在尝试学习如何与json api接口。 在文档中,他们给了我一个示例: 如果我将其作为命令运行,它工作正常,以json格式为我提供数据 我认为我在这方面是正确的: 但显然不是因为我不知道如何处理这个命令的-H部分 curl -H "APIKey:My:ApI;key;" -H "Content-Type:.../json" "https://urlofapp.com/API/GetTransaction" -d "{ 'CustomerID':'12345','EndDate':'2018-

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

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

我认为我在这方面是正确的:

但显然不是因为我不知道如何处理这个命令的-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脚本


希望它会有用。

直接处理卷曲通常会带来痛苦。有许多库可以帮助进行这样的调用,这要简单得多

以下是一些:

  • 简单而严谨:
  • 拥有你可能想要的一切:

命令中的
H
部分代表HTTP头。显示您的代码
H
是HTTP头。到目前为止,您的代码是什么?如果没有代码,我就无能为力。我已经用我目前拥有的更新了。为-H“Content Type:…/json”提供一些上下文。Praneth之所以将“application/json”作为此内容类型,是因为您正在将json编码的数据传递给此API(您的POST数据)。如果要传递XML编码的数据,则需要将其设置为“内容类型:application/XML”。这有助于API了解如何解析数据。