Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl and PHP not passing new line correctly when sending message to slack via API

I am trying to send slack message with php using curl. I'm able to send the message via command line to slack with curl no problem from an example online. My problem is converting it to php. When I use curl via php a new line \n does not get passed as a new line. It comes as text.

Here is my curl example that works and will send a new line

curl -X POST -H 'Authorization: Bearer xxxxx-xxxxxx-xxxxx-xxxxx' -H 'Content-type: application/json' --data '{"username":"Robot_Savant","channel":"recieved_test","as_user":"false","text":"First Line of Text\nSecond Line of Text"}' https://slack.com/api/chat.postMessage

Curl output:

First Line of Text

Second Line of Text

Here is my php code.

<?php

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();

$data = http_build_query([
    "channel" => '#recieved_test', //"#mychannel",
    "text" => 'First Line of Text\nSecond Line of Text', //"Hello, Foo-Bar channel message.",
    "as_user" => "false",
    "username" => "Robot_Savant"
]);
curl_setopt($ch, CURLOPT_URL, "https://slack.com/api/chat.postMessage");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Authorization: Bearer xxxxx-xxxxxx-xxxxx-xxxxx";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

?>

Curl via Php Output:

First Line of Text\nSecond Line of Text

I'm not sure how to get this to work. Any help would be great. I've tried lots of different header settings. Both pieces of code I've pulled from either stackoverflow or slack api examples.

like image 729
ScottEdge Avatar asked Jan 24 '26 10:01

ScottEdge


1 Answers

Change:

"text" => 'First Line of Text\nSecond Line of Text',

To:

"text" => "First Line of Text\nSecond Line of Text",

Using single quotes in PHP will literally output the \n as \n, not as a linebreak character.

like image 147
Robert Avatar answered Jan 27 '26 00:01

Robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!