PHP将JSON字典列表作为POST数据发送

时间:2016-07-05 11:59:35

标签: php api rest

您好我正在尝试使用PHP向API发送帖子请求。

我有以下代码。 API期望产品是像

这样的词典列表
[{"id":1, "name": "nyan"}, {"id": 2, "name": "cat"}] 

我有以下代码,似乎正确发送它,但API不接受它,我假设它与PHP数组编码的方式有关,但无法真正解决它,任何帮助表示赞赏。

<?php
$data = array(
  key => "API_KEY",
  private_key => "PRIVATE_API_KEY",
  products => array(array(id => 73,
  name => "A nice t-shirt",
  description => "A nice t-shirt with a picture of a cat",
  price => 9.95,
  brand => "Cat t-shirts",
  category => 11,
  rating => 5))
);
$data_string = json_encode($data);

$ch = curl_init('http://api.clerk.io/v2/product/add');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: application/json');

$result = curl_exec($ch);
echo $result;

3 个答案:

答案 0 :(得分:0)

您无需将其转换为 JSON字符串

请删除以下行

{
"Id": "foo",
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "foo",
        "Action": "s3:*",
        "Effect": "Allow",
        "Resource": "arn:aws:s3:::bar",
        "Principal": {
            "AWS": [
                "arn:aws:iam::foo"
            ]
        }
    }
]
}

并更新以下行,

$data_string = json_encode($data);
  

http_build_query()从Array生成URL编码的查询字符串。

答案 1 :(得分:0)

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));

在标题中添加内容长度

答案 2 :(得分:0)

$data = array(
    key => "API_KEY",
    private_key => "PRIVATE_API_KEY",
    products => array(
            array(id => 73,
                name => "A nice t-shirt",
                description => "A nice t-shirt with a picture of a cat",
                price => 9.95,
                brand => "Cat t-shirts",
                category => 11,
                rating => 5
            )
        )
);
$data_string = json_encode($data);

echo '<br>'.$data_string;

您将从“产品”键获取产品词典。所以你只需要将'产品'密钥数据传递给API。