2012-10-08 27 views
1

我試圖使用PHP API呈現SoundCloud HTML5小部件,但每次運行命令時都認爲應該返回小部件的HTML,我只是得到一個異常:使用PHP API呈現SoundCloud小部件專用軌跡

The requested URL responded with HTTP code 302 

我意識到這是一個重定向。我不知道的是,爲什麼這是我得到的所有東西,或者如何處理它以實際獲得小部件HTML。

的API文檔說嵌入使用PHP,你應該這樣做的小部件:

<?php 
    require_once 'Services/Soundcloud.php'; 

    // create a client object with your app credentials 
    $client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET'); 

    // get a tracks oembed data 
    $track_url = 'http://soundcloud.com/forss/flickermood'; 
    $embed_info = $client->get('/oembed', array('url' => $track_url)); 

    // render the html for the player widget 
    print $embed_info['html']; 

我運行此:

// NB: Fully authorised SoundCloud API instance all working prior to this line 
// $this->api refers to an authorised instance of Services_Soundcloud 

try { 
     $widget = array_pop(
      json_decode($this->api->get('oembed', array('url' => $track_url))) 
     ); 

     print_r($widget); 

    } catch (Exception $e) 
    { 
     print_r($e->getMessage()); 
    } 

其中 「track_url」 其實是URL在使用相同的API在應用程序的較早版本中向SoundCloud請求跟蹤對象時,我會回來。

我沒有真正確定這個URL是擺在首位正確的,因爲賽道的對象,我回去給的形式「URI」:

[uri] => https://api.soundcloud.com/tracks/62556508 

文檔實例都有直http://soundcloud.com/username/track-permalink URL - 但即使使用公共跟蹤的已知路徑,嘗試運行API oembed方法失敗...我仍然得到302異常。

最後,在'get'命令中提到了將allow_redirects設置爲false,但是當我將這些參數添加到用於構建API查詢的參數時,這沒有任何影響。我也嘗試添加額外的cURL選項,但這也沒有效果。

我已經明確地啓用了對SoundCloud中的軌道的API訪問。

這種撞擊我的頭在牆上的種類。如果任何人有任何指示,我會非常感謝聽到他們。爲了清楚起見,我可以通過我創建的API實例訪問所有用戶數據,評論等,因此它似乎工作正常。

+0

'HTTP代碼302'很直接......這意味着你被重定向.....'CURLOPT_FOLLOWLOCATION'只有在你使用'download'方法時纔會被激活 – Baba

+0

我明白302是一個重定向。我不明白的是爲什麼會這樣。儘管如此,感謝CURLOPT_FOLLOWLOCATION的澄清。 – raffjones

+0

保羅奧斯曼的下面的解決辦法是訣竅 - 非常好。只是簡要說明(我第一次錯過) - 嘗試使用PRIVATE跟蹤URL時,請確保使用跟蹤頁面右側面板中顯示的「Secret Link」URL。這將是曲目的最後一個隨機字符串的漂亮的URL。 – raffjones

回答

2

感謝您指出這一點。文檔中存在一個導致你誤入歧途的錯誤。對於那個很抱歉。我已經更新了文檔來修復該錯誤。下面是更新後的代碼示例:

<?php 

require_once 'Services/Soundcloud.php'; 

// create a client object with your app credentials 
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET'); 
$client->setCurlOptions(array(CURLOPT_FOLLOWLOCATION => 1)); 

// get a tracks oembed data 
$track_url = 'http://soundcloud.com/forss/flickermood'; 
$embed_info = json_decode($client->get('oembed', array('url' => $track_url))); 

// render the html for the player widget 
print $embed_info->html; 

注意區別:

  • 您需要如上評論提到CURLOPT_FOLLOWLOCATION設置爲1。
  • 你需要用從$client->get返回在json_decode
  • 結果是stdClass對象,而不是一個Array等等html酒店使用->運營商進行訪問。

希望有幫助。如果您仍然遇到問題,請隨時發表評論,我會修改我的答案。

+0

棒極了 - 就是那個!非常感謝保羅。 – raffjones

+0

我在Ruby gem的專用軌道上遇到類似的問題。當我在私人軌道上運行$ sc_client.get('/ oembed',:url => track.permalink_url)時,我得到一個404 - 公共軌道正常工作 - 私人軌道是「爲所有人啓用的小部件」和「啓用了應用程序「 –

+0

從頭開始,你必須使用#secret_uri –