2014-12-03 58 views
1

我不是很好使用PHP和cURL,通常我只是用javascript或C#打電話,但是我正在使用wordpress,因此C#不可能,而且我在調用url中有一個apikey,所以我想知道我是否可以得到一些幫助。在JavaScript中,電話會。PHP curl headers

 var forecastOptions = { 
     "cache": false, 
     "dataType": "jsonp", 
     "url": callSite 
    }; 
    var forecastRequest = $.ajax(forecastOptions); 

我這樣做是爲了我的可讀性。我也不想打開「allow_url_fopen選項」

編輯

因此,這是我現在有。

<?php 
     $api_key = 'xxxxxxxxxx'; 
     $latitude = "40.5122"; 
     $longitude = "-88.9886"; 
     $API_ENDPOINT = 'https://api.forecast.io/forecast/'; 

     $request_url = $API_ENDPOINT . 
     $api_key . '/' . 
     $latitude . ',' . $longitude; 

     $ch = curl_init(); 

     $headers = array(
      'Content-Type: application/json', 
      'Accept: application/json' 
     ); 
     curl_setopt($ch, CURLOPT_URL, $request_url); 
     curl_setopt($ch, CURLOPT_HEADER, $headers); 

     $result = curl_exec($ch); 

     $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

     curl_close($ch); 


     $content = json_decode($result, true); 

     if(empty($content)){ 
      print_r("Empty"); 
     } 

    ?> 

這是告訴我,$內容是空的。如果有什麼,我錯過了什麼。

回答

0

您可以參考this page獲取有關PHP所有cURL函數的文檔。另外,我不熟悉JS中的cURL,所以我不確定如何匹配你的選項,但是PHP的所有cURL選項可以在here找到。

作爲一個例子,它應該是這個樣子:

// create a new cURL resource 
$ch = curl_init(); 

// set URL and other appropriate options 
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 

// grab URL and pass it to the browser 
curl_exec($ch); 

// close cURL resource, and free up system resources 
curl_close($ch); 
2

多德先生是正確的,但使用JSONP的建議,你在做一個跨站點請求。由於PHP通常在服務器端運行,因此您不必擔心這一點。你只需要確保你使用的url返回JSON。您可能要頭添加到您的要求是這樣的:

$headers = array(
    'Content-Type: application/json', 
    'Accept: application/json' 
); 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

當你執行的要求,你可以檢索這樣的響應和HTTP狀態:

// Get the result 
$result = curl_exec($ch); 

// Get the status 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

// Close the session 
curl_close($ch); 

//Parse the JSON 
$result_arr = json_decode($result, true); 
+0

我已經更新了我的代碼,但我沒有收到任何請求。我在代碼中丟失了什麼嗎?我正試圖從forecast.io api中提取。 – pormus 2014-12-03 18:22:24

+0

你應該嘗試從瀏覽器中使用的URL,看它是否返回任何東西。 您還應該從上面的$ httpCode中檢查HTTP狀態。 – 2014-12-03 19:26:20

+0

我做了print_r($ httpCode),它給了我0.我接通了網址,並把它放在瀏覽器的網址中,以確保它是正確的網址(它是)然後我拿了並粘貼該網址代替$ request_url。我仍然得到相同的結果。 – pormus 2014-12-03 19:33:14