I'm trying to create a function in Wordpress that sends data with JSON through Curl to a Slack webhook. I'm more used to the way you structure arrays and objects in JavaScript, so doing this in PHP before it's being encoded to JSON is a bit confusing to me.
This is how the PHP for this encoding looks:
$data = json_encode(array(
"username"=> "Email Notifier",
"mrkdwn"=> true,
"icon_emoji"=> ":email:",
"text" => "*Name:* {$posted_data["your-name"]}\n*Email:* {$posted_data["your-email"]}\n*Subject:* {$posted_data["your-subject"]}\n*Message:*\n >{$posted_data["your-message"]}",
));
// Finally send the data to Zapier or your other webhook endpoint
$ch = curl_init("https://hooks.slack.com/services/Txxxxxx/Bxxxxxx/xxxxxxxxxxxxxxx"); // replace with your Zapier webook
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); //Optional timeout value
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //Optional timeout value
$result = curl_exec($ch);
curl_close($ch);
return $result;
This sends the following JSON to the Slack webhook successfully:
{
"username": "Email Notifier",
"mrkdwn": true,
"icon_emoji": ":email:",
"text": "whatever" //generated by using PHP variables
}
I now want to be able to output the text property and additional properties within an array called attachment, like this:
{
"username": "Email Notifier",
"mrkdwn": true,
"icon_emoji": ":email:",
"text": "You have received a new message!",
"attachment": [
{
"text": "whatever", //generated by using PHP variables
"fallback": "Required plain-text summary of the attachment.",
"color": "#36a64f",
}
]
}
But I'm not really sure how to solve this with the PHP syntax. Any ideas?
$posted_data['your-name']instead of doubles.array('attachment' => array(array('text' => 'whatever', ...)))json_encode()handles the proper encoding as JSON.print_r(json_decode($sample));and see what array structure you need