通过 API 向 slack 发送消息时,Curl 和 PHP 未正确传递新行

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

我正在尝试使用 curl 通过 php 发送松弛消息。我可以通过命令行将消息发送到 slack with curl 从在线示例中没有问题。我的问题是将它转换为 php。当我通过 php 使用 curl 时,新行 \n 不会作为新行传递。它以文本形式出现。

这是我的 curl 示例,它可以工作并且会发送一个新行

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

这是我的 php 代码。

<?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

我不确定如何让它工作。任何帮助都会很棒。我尝试了很多不同的 header 设置。我从 Whosebug 或 slack api 示例中提取的两段代码。

变化:

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

收件人:

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

在 PHP 中使用单引号会将 \n 直接输出为 \n,而不是换行符。