【问题标题】:Curl and PHP not passing new line correctly when sending message to slack via API通过 API 向 slack 发送消息时,Curl 和 PHP 未正确传递新行
【发布时间】:2018-04-01 13:11:04
【问题描述】:

我正在尝试使用 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

卷曲输出:

第一行文字

第二行文字

这是我的 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);

?>

通过 PHP 输出卷曲:

第一行文字\n第二行文字

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

【问题讨论】:

  • 尝试将您的消息用双引号括起来:"text" =&gt; "First Line of Text\nSecond Line of Text",

标签: php curl slack-api


【解决方案1】:

变化:

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

收件人:

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

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

【讨论】:

  • 嗯,这很简单,我花了好几个小时寻找答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 2022-11-11
  • 2020-08-15
  • 1970-01-01
相关资源
最近更新 更多