2016-03-27 110 views
-1

我正在嘗試使用cURL發送POST請求的JSON文本。 的JSON文本是:通過PHP POST發送JSON(cURL)

{ 「通道」: 「我的頻道」, 「用戶名」: 「TriiNoxYs」, 「文」: 「我的文字」}

我用這代碼:

<?php 

    $data = array(
     'username' => 'TriiNoxYs', 
     '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文本,像這樣:

{「通道」:「我的陳蔭羆el「,」username「:」TriiNoxYs「,」text「:」我的文本「,」附件「:[{」text「:」Line 1「,」color「:」#000000「},{」text「 「2號線」, 「色」: 「#FFFFFF」}]}

於是,我就加入到我的$ data數組:

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

但不工作,後發送,但我的「附件」被忽略...... 我也試圖從一個Linux終端與此代碼直接發送POST:

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

,它的工作... 我只是不明白爲什麼它與手動POST,而不是與PHP /捲曲...

感謝您的答案,TriiNoxYs。 PS:對不起我的英文不好,我是法國人...

+0

我懶得檢查規則看看我是否可以用法語回答,所以現在我會堅持使用英語。 「附件」數據被忽略的事實是什麼意思?你的意思是他們不存在$ _POST?或者他們是空的? – Technoh

+0

我該如何檢查? – TriiNoxYs

+0

你可以在接收端'var_dump'完整'$ _POST'來查看確切的JSON字符串。 – Technoh

回答

0

你正在做雙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" 
     ) 
    ) 
); 
+0

Ooooh好吧,它很愚蠢...... 感謝您的幫助! :) – TriiNoxYs