PHP,cURL,REST_API,JSON-使用方法“ PUT”在数据字段中插入值

时间:2018-10-11 10:38:21

标签: php json api curl put

我使用以下代码通过API将值插入数据库的某些字段。我必须使用的方法是PUT

<?ph
header('Content-type: text/html; charset=utf-8');
error_reporting(E_ALL);
//ini_set('display_errors', '1');
$id = $_POST["id"];             
// URL to fetch
$url = "https://bpk.bs.picturemaxx.com/api/v1/editing/classifications/42/elements/2155984";
// Setting the HTTP Request Headers
$User_Agent = 'Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0';

$request_headers = array('Contect-Type:text/xml', 'Accept:text/xml');
$request_headers[] = 'Accept: application/json';
$request_headers[] = 'Content-type: application/json';
$request_headers[] = 'Accept-Encoding:  gzip, deflate, identity';
$request_headers[] = 'X-picturemaxx-api-key: K3f4e7m8dalksjdwdkkk';
$request_headers[] = "Authorization: Bearer token";


$dataj = array("classification_element_name" => 'string');
$data_json = json_encode($dataj);

 $ch = curl_init($url);
 // Set the url
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_USERAGENT, $User_Agent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

// Execute
$result = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any).
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Closing
curl_close($ch);

if ($code == 200) {
$result = json_decode($result, true);
print_r($result);
} else {
echo 'error ' . $code;
}
?>

然后我得到答复

{
"request": {
"date": "2018-10-11T11:47:10+02:00",
"uid": "20181011-114710-03640bb2dcf2616d7"
},

到目前为止,一切都很好。但是很遗憾,这些值没有输入到所需的数据库字段中。

API中的Example-JSON-Body如下所示

{
  "classification_element_parent_id": 0,
  "classification_element_matchcode": "string",
  "classification_element_foreignref": "string",
  "localized": {
    "en-us": {
      "classification_element_name": "string"
    },
    "de-de": {
      "classification_element_name": "string"
    }
  }
}

JSON代码的一部分看起来像这样

enter image description here

那么我如何例如在字符串classification_element_name中传递值,该值是数组item / localized / de-de的一部分?

我之前也尝试过此数组->

$dataj['item']['localized']['de-de'] => 'string';

$data_json = json_encode($dataj);

1 个答案:

答案 0 :(得分:0)

您必须构建一个像这样的数组:

$dataj = array (
  'classification_element_parent_id' => 0,
  'classification_element_matchcode' => 'string',
  'classification_element_foreignref' => 'string',
  'localized' => 
  array (
    'en-us' => 
    array (
      'classification_element_name' => 'string',
    ),
    'de-de' => 
    array (
      'classification_element_name' => 'string',
    ),
  ),
);