2015-07-03 126 views
0

您好我想使JSON請求一個API,但我不知道如何,因爲我從來沒有工作過的類似的東西。如果有人能幫助我,我會很感激。PHP JSON請求

下面是我需要請求:

請求負載:

{ 
    "sessionId": "1234567890", 
    "availabilityRequest": { 
     "checkInDate": "29042014", 
     "checkOutDate": "", 
     "noRooms": 1, 
     "noNights": 1, 
     "userType": "leisure", 
     "rateType": "standard", 
     "roomPreference": [ 
      { 
       "noAdult": 1, 
       "noChild": 0 
      } 
     ], 
     "siteCode": [ 
      "GB0758", 
      "GB0746", 
      "GB0738", 
      "GB0755", 
      "GB0742" 
     ], 
     "includeDisabled": "F" 
    } 
} 

這是我做了什麼,但我得到的錯誤Array ([error] => Array ([code] => 4007 [message] => Invalid JSON POST data (unable to decode):))

 $postData = '{ 
       "sessionId":"1234567890", 
       "availabilityRequest": 
       { 
        "checkInDate": "29042014", 
        "checkOutDate": "", 
        "noRooms": 1, 
        "noNights": 1, 
        "userType": "leisure", 
        "rateType": "standard", 
        "roomPreference": 
         [ 
          { "noAdult":1, "noChild":0 } 
         ], 
        "siteCode": 
         [ 
         "GB0758","GB0746","GB0738","GB0755","GB0742" 
         ], 
        "includeDisabled":"F" 
       } 
      }'; 

     $ch = curl_init($url); 
     curl_setopt_array($ch, array(
     CURLOPT_POST => TRUE, 
     CURLOPT_RETURNTRANSFER => TRUE, 
     CURLOPT_POSTFIELDS => $postData)); 

     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

     // Send the request 
     $response = curl_exec($ch); 

     // Check for errors 
     if($response === FALSE){ 
      die(curl_error($ch)); 
     } 

     // Decode the response 
     $responseData = json_decode($response, TRUE); 

     // Print the date from the response 
     print_r($responseData); 

我會真的很感激有人可以幫助我。謝謝

+0

什麼是你'$ postData'模樣。 – PHPhil

+0

我編輯過的帖子顯示了我的$ postData看起來像 – user4676307

回答

0

我真的不能測試這個,因爲我沒有URL來測試它,但你可以嘗試設置一個頭。

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($postData))); 
1

您的JSON無效。使用工具如http://jsonlint.com/

您應該添加的其他}到年底將其關閉驗證。那麼你將有一個有效的JSON。

+2

Json只在代碼區域中沒有包含最後一個括號的問題中有效。 – PHPhil

+1

爲什麼測試和發現錯誤的努力的負面點? –