【问题标题】:Add json data to existing array using curl使用 curl 将 json 数据添加到现有数组
【发布时间】:2018-09-14 20:33:33
【问题描述】:

我正在使用 PHP 通过 curl 发送 HTML 发布请求。我想在 URL 处向现有 JSON 数组添加更多数据。如果我发布请求,它会替换数据还是将其添加到现有数组中?目前,我正在写:

// Setup cURL
$ch = curl_init('http://www.barn-door.co.uk/wp-json/geodir/v1/farms'); 

curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
    'Authorization: '.$authToken,
    'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
echo $responseData['published'];

其中 $postData 是我的 json 格式数据。

谢谢:)

【问题讨论】:

  • 替换当前数据。只需在编码和设置之前修改$data-array。
  • 注意: 这不是您使用 cURL 发送 json 的方式。来自有关 CURL_POSTFIELDS 的手册:“此参数可以作为 urlencoded 字符串(如 'para1=val1&para2=val2&...')或作为字段名称作为键和字段数据作为值的数组传递。”我>。您应该在正文中发送 json 字符串,并确保将内容类型设置为 application/json

标签: php html json curl post


【解决方案1】:

您可以在发送前合并您的数据

// original data
$data = array("firstname" => "Foo");

// your new data
$additionalData = array("surname" => "Bar");

// merge/overwrite
$data = array_merge($data, $additionalData);

//result print_r($data); will output array("firstname" => "Foo", "surname" => "Bar")

【讨论】:

    【解决方案2】:

    这应该适合你。

    $arraydata = array("name" => "test","email" =>"test@test.com"); 
    
    $senddata = array_merge($_POST, $arraydata); // $_POST will hold values from form submission
    
    $data_string = json_encode ( $senddata );
    
    $curl = curl_init ();
    curl_setopt ( $curl, CURLOPT_URL, $url );
    curl_setopt ( $curl, CURLOPT_POST, true );
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data_string ); // Insert the data
    curl_setopt ( $curl, CURLOPT_HTTPHEADER, array (
            'Accept: application/json' 
    ) );
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true ); // Make it so the data coming back is put into a string
    $result = curl_exec ( $curl );
    curl_close ( $curl );
    

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多