在PHP中创建此JSON输出?

时间:2016-03-03 17:56:24

标签: php json

如何使用PHP创建此JSON输出?

{
  "external_ref": "12345",
  "sale_datetime": "2016-03-01 22:09:00",
  "customer_name": "Foo Bar",
  "shipping_address_1": "123 Test Street",
  "shipping_address_2": "",
  "shipping_address_3": "City",
  "shipping_address_4": "County",
  "shipping_postcode": "AB12 3AB",
  "shipping_country": "England",
  "shipping_country_code": "GB",
  "shipping_method": "STANDARD",
  "phone": "01234567890",
  "items": [
    {
        "external_ref": "12345",
        "style": "mens",
        "size": "Medium",
        "color": "White",
        "print_location": "front",
        "print_x_offset": "0",
        "print_y_offset": "0",
        "quantity": 1,
        "external_url": "url.png",
        "external_thumbnail_url": "url.jpg"
    }
  ]
}

我自己尝试了这个(下面),但它没有提交给我发送给它的API:

//Initiate cURL.
$ch = curl_init($url);

$item = array(
  array(
    "external_ref" => 12345,
    "style" => "mens",
    "size" => "Medium",
    "color" => "White",
    "print_location" => "FRONT",
    "print_x_offset" => "0",
    "print_y_offset" => "0",
    "quantity" => 1,
    "external_url" => "url.png",
    "external_thumbnail_url" => "url.jpg"
  )
);

//The JSON data.
$jsonData = array(
    "external_ref"=> 12345,
    "sale_datetime" => "2016-03-01 22:09:00",
    "customer_name" => "Foo Bar",
    "shipping_address_1" => "123 Test Street",
    "shipping_address_2" => "",
    "shipping_address_3" => "City",
    "shipping_address_4" => "County",
    "shipping_postcode" => "AB12 3AB",
    "shipping_country" => 'England',
    "shipping_country_code" => "GB",
    "shipping_method" => "STANDARD",
    "phone" => "01234567890",
    "items" => $item
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

//Execute the request
$result = curl_exec($ch);

我错过了一些重要的东西吗?此问题顶部的第一位JSON代码确实正确提交。当我尝试使用此PHP复制该JSON时,它不会提交。

2 个答案:

答案 0 :(得分:2)

我运行你的代码并得到:

np.where

sale_datetime格式的差异:

  • 2016年3月1日22:09:00 - 您想要的格式
  • 2016-03-01 22:09:00 - 这个fromat的PHP输出

和external_ref变为整数而不是字符串

答案 1 :(得分:0)

原来我的网址提交的请求错过了一个'?'我在哪里添加'token ='。糟糕!