2012-06-01 59 views
0

我在PHP中使用捲曲來調用API所有標題。捲髮不返回

根據他們documentation,他們正在返回的頁面的頭部內返回「驗證回調」。

它完美,當我將URL粘貼到瀏覽器中,但捲曲似乎離開它。

這裏是我的代碼

$ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, 'http://api.themoviedb.org/3/authentication/token/new?api_key=[MY_API_KEY]&language=en'); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $results = curl_exec($ch); 
    $headers = curl_getinfo($ch); 

這裏是返回頭

Array 
    (
     [url] => http://api.themoviedb.org/3/authentication/token/new?api_key=[MY_API_KEY]&language=en& 
     [content_type] => application/json;charset=utf-8 
     [http_code] => 200 
     [header_size] => 470 
     [request_size] => 137 
     [filetime] => -1 
     [ssl_verify_result] => 0 
     [redirect_count] => 0 
     [total_time] => 0.109 
     [namelookup_time] => 0 
     [connect_time] => 0.047 
     [pretransfer_time] => 0.047 
     [size_upload] => 0 
     [size_download] => 116 
     [speed_download] => 1064 
     [speed_upload] => 0 
     [download_content_length] => 116 
     [upload_content_length] => 0 
     [starttransfer_time] => 0.109 
     [redirect_time] => 0 
     [certinfo] => Array 
      (
      ) 

    ) 

據我所知,一切是正確的。 Curl返回我需要的數據,只是不正確的標題。

任何幫助表示讚賞!

+0

我知道這解決不了任何問題,但只是想指出的是,如果你能夠利用周圍捲曲的包裝,如[pecl_http(http://us.php.net/http),像那些能非常愉快做。 – Roberto

回答

2

你現在正在做正確的通過curl_getinfo()僅獲取該網頁上的OPT列表中的信息獲取有關頭存儲的信息。

你應該做的,而不是是返回頭,然後手動分開吧:

curl_setopt($ch, CURLOPT_HEADER, 1); 
// The rest of your options 
$output = curl_exec($ch); 

// Since the end of the header is always delimited by two newlines 
$output = explode("\n\n", $output, 2); 
$header = $output[0]; 
$content = $output[1]; 

這是更多的工作,但將讓你真正的頭。

+0

這工作完美,謝謝! –

2

這是我的代碼做了建議的頭被放入$頭陣列什麼phsource

# Extract headers from response 
preg_match_all('%HTTP/\\d\\.\\d.*?(\\r\\n|\\n){2,}%si', $curl_result, $header_matches); 
$headers = preg_split('/\\r\\n/', str_replace("\r\n\r\n",'',array_pop($header_matches[0]))); 

# Convert headers into an associative array 
if(is_array($headers)) 
{ 
    foreach ($headers as $header) 
    { 
    preg_match('#(.*?)\:\s(.*)#', $header, $header_matches); 
    if(isset($header_matches[1])) 
    { 
     $headers[$header_matches[1]] = $header_matches[2]; 
     $headers['lowercase'][strtolower($header_matches[1])] = $header_matches[2]; 
    } 
    } 
} 

# Remove the headers from the response body 
$curl_result = preg_replace('%HTTP/\\d\\.\\d.*?(\\r\\n|\\n){2,}%si','',$curl_result); 

你可能要替換\ r \ n,其中PHP_EOL你認爲合適的

+0

太好了,我會試試2的組合,謝謝! –