首页 > 解决方案 > 使用 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);

标签: phpapicurl

解决方案


-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/

希望它会有用。


推荐阅读