2014-09-05 54 views
0

你好我在與張貼JSON陣列捲曲到我的API的一個問題,後JSON陣列使用curl

JSONData=' 
     { 

      "customerCode": "DUMMY", 
      "fromLocation": { 
      "suburbName": "MELBOURNE", 
      "postCode": "3000", 
      "state": "VIC" 
      }, 
      "toLocation": { 
      "suburbName": "SYDNEY", 
      "postCode": "2000", 
      "state": "NSW" 
      }, 
      "goods": [ 
      { 
       "pieces": "2", 
       "weight": "3", 
       "width": "10", 
       "height": "20", 
       "depth": "12", 
       "typeCode": "ENV" 
      } 
      ] 
      } '; 

,我使用此代碼通過數組,但它不工作

$data_string = stripslashes($JSONData); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                   
    'Content-Type: application/json',                     
    'Content-Length: ' . strlen($data_string)                  
)); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, array('JSONData'=>$data_string) 

); 

請幫我通過JSON數組。

+0

而不是POSTFIELDS我們可以用什麼來傳遞json數組 – user3931851 2014-09-05 05:20:41

+0

對不起,我弄錯了。我想你只是想使用'curl_setopt($ ch,CURLOPT_POSTFIELDS,$ data_string)'。僅供參考,滾動您自己的JSON並不是一個好主意。在PHP中構建一個數組,然後使用'json_encode()'而不是 – Phil 2014-09-05 05:21:42

+0

如果這不起作用,我推薦使用像[Guzzle]這樣的HTTP庫(http://guzzle.readthedocs.org/en/latest/)。比使用cURL lib更容易 – Phil 2014-09-05 05:30:46

回答

0
$username='xxx'; 
$password='xxx'; 
$url='http://apiurl'; 
$opts = array('http' => 
     array(
      'method' => 'POST', 
      'header' => array('Content-type: application/json', 'Authorization: Basic '.base64_encode($username.':'.$password)), 
      'content' => $JSONData 
     ) 
    ); 
    $context = stream_context_create($opts); 
    $response = file_get_contents($url, false, $context); 
    echo 'response: '.$response; 
0

由於您指定的內容類型爲application/json,因此您必須json_encode完整數據。因此,與嘗試,

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('JSONData'=>$data_string)); 

作爲一個側面說明,你也可以用curl_setopt($ch, CURLOPT_POST, "TRUE");取代curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");