I'm using PHP to send an HTML post request using curl. I want to add more data to an existing JSON array at an URL. If I post a request, does it replace the data or does it add it to the existing array? Currently, I'm writing:
// 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'];
where $postData is my data in json format.
Thanks :)
you can merge your data before sending
// 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")
This should work for you.
$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 );