通过PHP POST(cURL)发送JSON


Send JSON via PHP POST (cURL)

我正在尝试使用cURL发送带有POST请求的JSON文本。JSON文本为:

{"channel":"My channel","username":"我的用户名","text":"My text"}

我使用的是这个代码:

<?php
    $data = array(
        'username'    => 'My username',
        'channel'     => 'My channel'
        'text'        => 'My text',
    );                                                                    
    $data_json = json_encode($data);            
    $curl = curl_init('my-url');                                                                      
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_json);       
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($ch, CURLOPT_POST, 1);        
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_json))                                                                       
    );                                                                                                                   
    $result = curl_exec($curl);
    echo $result ;
?>

代码有效,但我想在JSON文本中添加一个"附件"数组,如下所示:

所以我试着把它添加到我的$data数组中:

'attachments' => '[{"text":"Line 1", "color":"#000000"}, {"text":"Line 2", "color":"#ffffff"}]',

但不起作用,帖子被发送了,但我的"附件"被忽略了。。。我还尝试直接从Linux终端发送POST,代码是:

POST https://myurl.com
payload={"channel": "My channel", "username": "My username", "text": "My text", "attachments": [{"text":"Line 1","color":"#000000"},{"text":"Line 2","color":"#ffffff"}]}

它正在发挥作用。。。我只是不明白为什么它使用手动POST而不使用php/ccurl。。。

谢谢你的回答
PS:很抱歉我英语不好,我是法国人。。。

您正在执行双重json_encode。

首先,比较这两个:

$json1 = json_encode([
  'firstname' => 'Jon',
  'lastname' => 'Doe',
  'hp' => [
    'cc' => '+1',
    'number' => '12345678'
  ]
);
//You should get
//{"firstname":"Jon","lastname":"Doe","hp":{"cc":"+1","number":"12345678"}}

这个:

$json2 = json_encode([
  'firstname' => 'Jon',
  'lastname' => 'Doe',
  'hp' => "['cc' => '+1', 'number' => '12345678']"
]);
//You should get
//{"firstname":"Jon","lastname":"Doe","hp":"['cc' => '+1', 'number' => '12345678']"}

你看到问题了吗?您将attachments密钥设置为json编码的字符串,因此当它被发送到目标服务器时,它将被视为字符串'[{"text":"Line 1", "color":"#000000"}, {"text":"Line 2", "color":"#ffffff"}]',而不是预期的文本颜色对数组。这里没有什么花哨的,这纯粹是一个粗心的错误:)

因此,为了解决这个问题,不要在attachments密钥中发送json编码的字符串,而是使用以下内容:

$data = array(
    'username'    => 'TriiNoxYs',
    'channel'     => 'My channel'
    'text'        => 'My text',
    'attachments' => array(
        array(
            "text" => "Line 1",
            "color" => "#000000",
        ),
        array(
            "text" => "Line 2",
            "color" => "#ffffff"
        )
    )
);