使用PHP

时间:2018-07-12 13:08:17

标签: php json

我正在尝试使用PHP将json数据发布到Api,但是它返回无效数据的错误。以下是Json请求格式

我的Json请求

{
  "Detail": {
    "ServiceRequestVersion": "1.0",
    "Token": "my token goes here",
  },
  "CustomerInformation": {
    "ProductVerID": "706",
    "ProductID": "619",
    "List": [
      {
        "FirstName": "John",
        "LastName": "Doe"

      }
    ]
  }
}

我想我的问题是我如何通过在下面的数组中传递请求来尝试发送请求

$data_string = array(
"Detail[0].ServiceRequestVersion" => "1.0",
"Detail[0].Token => "my token goes Here",

 "CustomerInformation[0].ProductVerID" => "709",
 "CustomerInformation[0].ProductID" => "200",
 "List[0].[FirstName]" => "John",
 "List[0].[LastName]" => "Mark"

); 

这是完整的代码。有人可以帮我修复代码吗?

<?php


$data_string = array(
"Detail[0].ServiceRequestVersion" => "1.0",
"Detail[0].Token => "my token goes Here",

 "CustomerInformation[0].ProductVerID" => "709",
 "CustomerInformation[0].ProductID" => "200",
 "List[0].[FirstName]" => "John",
 "List[0].[LastName]" => "Mark"

); 

$data = json_encode($data_string); 
//$data = $data_string; 
$curl = curl_init();

curl_setopt_array($curl, array( 
CURLOPT_URL => "my api goes here", 
CURLOPT_RETURNTRANSFER => true, 
CURLOPT_ENCODING => "", 
CURLOPT_MAXREDIRS => 10, 
CURLOPT_TIMEOUT => 30, 
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 
CURLOPT_CUSTOMREQUEST => "POST", 
CURLOPT_POSTFIELDS => "$data", 
CURLOPT_HTTPHEADER => array( 
"accept: application/json", 
"authorization: my auth goes here", 
"content-type: application/json; charset=utf-8" 
), 
));

$result = curl_exec($curl); 
$err = curl_error($curl);

curl_close($curl);



if($result === false) {

 echo "data failed to be posted";
echo $result;
}

 else {
'Data successfully created';
}





if ($err) { 
echo "cURL Error #:" . $err; 
} else { 
echo $result; 
}
?>

2 个答案:

答案 0 :(得分:1)

用下面的代码替换$ data_string,然后检查:

    $data_string = array(
      "Detail" => array(
        "ServiceRequestVersion" => "1.0",
        "Token" => "my token goes Here"
      ),
      "CustomerInformation" => array(
        "ProductVerID" => "709",
        "ProductID" => "200",
      ),
      "List" => array(
        "FirstName" => "John",
        "LastName" => "Mark"
      )
    );

答案 1 :(得分:0)

请记住,您只是在创建数组或对象。一个PHP数组,就像其他任何PHP数组一样。然后,json_encode将该数组转换为JSON语法,从字面上将PHP属性映射到JSON属性。数组中的属性名称不用作任何东西,只能用作文字名称。它们不以任何方式用于控制结构。我不确定您是从何而来提出问题中奇异语法的想法。

就像想要在PHP中使用相同的数据结构一样,声明数组。

这将生成正确的结构:

$data_string = array(
  "Detail" => array(
    "ServiceRequestVersion" => "1.0",
    "Token" => "my token goes Here"
  ),
  "CustomerInformation" => array(
    "ProductVerID" => "709",
    "ProductID" => "200",
    "List" => array( 
      0 => array(
        "FirstName" => "John",
        "LastName" => "Mark"
      )
    )
  ),
);

有关演示,请参见https://eval.in/1035515