ScottEdge
ScottEdge

Reputation: 87

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.

Upvotes: 2

Views: 3983

Answers (1)

Robert
Robert

Reputation: 5973

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.

Upvotes: 10

Related Questions