任何你不需要創建和保存一個實際的JSON文件爲每個請求。您可以簡單地創建一個JSON字符串並將其作爲POST有效負載發送。就執行curl而言,您應該看到PHP Manual中的本地函數。具體而言,curl_init(),curl_setopt()和curl_exec()。下面是一個例子...
$url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=YOUR_API_KEY_HERE";
$postData = '{
"request": {
"passengers": {
"adultCount": 1
},
"slice": [
{
"origin": "BOS",
"destination": "LAX",
"date": "2016-05-10"
},
{
"origin": "LAX",
"destination": "BOS",
"date": "2016-05-15"
}
]
}
}';
$curlConnection = curl_init();
curl_setopt($curlConnection, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curlConnection, CURLOPT_URL, $url);
curl_setopt($curlConnection, CURLOPT_POST, TRUE);
curl_setopt($curlConnection, CURLOPT_POSTFIELDS, $postData);
curl_setopt($curlConnection, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curlConnection, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlConnection, CURLOPT_SSL_VERIFYPEER, FALSE);
$results = curl_exec($curlConnection);
你也可以使用一個數組來創造有效載荷,然後用json_encode()將其轉換成JSON字符串。
$postData = array(
"request" => array(
"passengers" => array(
"adultCount" => 1
),
"slice" => array(
array(
"origin" => "BOS",
"destination" => "LAX",
"date" => "2016-05-10"
),
array(
"origin" => "LAX",
"destination" => "BOS",
"date" => "2016-05-15"
)
)
)
);
然後用
curl_setopt($curlConnection, CURLOPT_POSTFIELDS, json_encode($postData));
感謝。有效。現在我從那裏得到了json的東西。現在問題是我無法解析它。我得到了:'print_r($ flightsarray [0] - > trips-> data-> airport [0]);'結果_Notice:嘗試獲取非object_的屬性。我也嘗試過'$ flightsarray [0] [1] [1]' – xampper
使用['json_decode()'](http://php.net/manual/en/function.json-decode.php)來轉換結果JSON到一個對象或數組中,無論你喜歡什麼。如果您有關於解析此API結果的具體問題,那麼您應該爲此創建一個新問題。 –