使用curl将json数据添加到现有数组

时间:2018-04-05 06:10:25

标签: php html json curl post

我使用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格式的数据。

谢谢:)

2 个答案:

答案 0 :(得分:0)

您可以在发送

之前合并数据
// 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")

答案 1 :(得分:0)

这应该适合你。

$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 );