Reputation: 7049
I was wondering how I could merge the variables at the top of my PHP file with the dict in my cURL POST method.
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
curl_setopt_array($curl, array(
CURLOPT_URL => "CUSTOM_URL",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"email_address\": \"[email protected]\", \"status\": \"subscribed\", \"merge_fields\": {\"FNAME\": \"Bob\", \"LNAME\": \"Dylan\"}}",
CURLOPT_HTTPHEADER => array(
"authorization: Basic UN:PW",
"cache-control: no-cache",
"content-type: application/json",
),
));
So essentially, how do I put First Name, Last Name, Email, etc into "{\"email_address\": \"[email protected]\", \"status\": \"subscribed\", \"merge_fields\": {\"FNAME\": \"Bob\", \"LNAME\": \"Dylan\"}}"
(to replace [email protected]
, Bob
, etc.)
Upvotes: 0
Views: 233
Reputation: 1306
I suggest you that use http_build_query
function. try this:
$postfields = [
'email_address' => $_POST['email'],
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $_POST['first_name'],
'LNAME' => $_POST['last_name']
]
]
curl_setopt_array($curl, array(
CURLOPT_URL => "CUSTOM_URL",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query( $postfields ),
CURLOPT_HTTPHEADER => [
"authorization: Basic UN:PW",
"cache-control: no-cache",
"content-type: plain/text",
],
));
Or with JSON:
$postfields = [
'email_address' => $_POST['email'],
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $_POST['first_name'],
'LNAME' => $_POST['last_name']
]
]
curl_setopt_array($curl, array(
CURLOPT_URL => "CUSTOM_URL",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode( $postfields ),
CURLOPT_HTTPHEADER => [
"authorization: Basic UN:PW",
"cache-control: no-cache",
"content-type: application/json",
],
));
Upvotes: 0
Reputation: 2023
Use json_encode.
$data = [
'email_address' => $_POST['email'],
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $_POST['first_name'],
'LNAME' => $_POST['last_name'],
],
];
...
CURLOPT_POSTFIELDS => json_encode($data),
...
Upvotes: 2
Reputation: 4302
I would use json_encode
to just create a whole new json string with the variables you need. The alternative would be trying to string replace on the json string.
$fields = json_encode([
'FNAME' => $_POST['first_name'],
'LNAME' => $_POST['last_name'],
'email_address' => $_POST['email'],
'status' => 'subscribed'
]);
Then in your output:
CURLOPT_POSTFIELDS => $fields
Upvotes: 2