使用PHP API为专用曲目渲染SoundCloud小部件



我正在尝试使用PHP API呈现SoundCloud HTML5小部件,但每次运行我认为应该返回小部件的HTML的命令时,我都会得到一个异常:

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"实际上是我在应用程序早期使用相同的API向SoundCloud请求跟踪对象时返回的url。

实际上,我一开始就不确定这个URL是否正确,因为我得到的跟踪对象给出的"uri"格式为:

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

文档示例都有一条直线http://soundcloud.com/username/track-permalinkURL-但即使使用公共轨道的已知路径,运行API oembed方法的尝试也会失败。。。我仍然得到302例外。

最后,有人提到在'get'命令中将"allow_redirects"设置为false,但当我将其添加到用于向API构建查询的参数中时,这没有任何效果。我还尝试添加其他cURL选项,但也没有效果。

我肯定已经启用了API访问SoundCloud中的曲目。

有点把我的头撞到墙上了。如果有人有什么建议,我将非常感激听到。为了清晰起见,我可以通过我创建的API实例访问所有用户数据、评论等,所以它看起来运行良好。

感谢您指出这一点。文档中有一个错误,导致您误入歧途。很抱歉。我已经更新了文档来修复这个错误。以下是更新后的代码示例:

<?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属性

希望能有所帮助。如果你仍然有问题,请随时发表评论,我会修改我的答案。

最新更新