我在写Last。FM脚本,显示您正在听的歌曲,我希望能够将艺术家链接到歌曲标题和所有内容。
我该怎么做呢?我的意思是,我假设用str_replace()
,但是怎么用呢?
最后一条路。FM格式的url是这样的;
http://last.fm/artist/This +是+ +带
所以基本上我要问的是,我如何使用$artist变量,并将这些空格转换为加号,但仅用于脚本中打印歌曲信息的部分。
下面是我的代码:
$uname = "USERNAME";
$key = "API KEY";
$json = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks=" . $uname . "&api_key=" . $key . "&format=json"); // Gets your data
if (strpos($json, 'nowplaying') !== false) {
list($currentsonginfo, $crap) = explode('{"nowplaying":"true"}}', $json);
list($crap, $v2) = explode('{"recenttracks":{"track":[{"artist":{"#text":"', $currentsonginfo);
list($artist, $restinfo) = explode('","', $v2);
list($crap, $currenttrack) = explode('"name":"', $restinfo); }
$playing = $artist . ' - ' . $currentrack; // Checks if a song is playing
if ($playing == ' - ') {
echo '<a href="http://last.fm/user/' . $uname . '/">';
echo "I'm not listening to anything."; // Only if you're not scrobbling
echo "</a>";
} else {
echo '<marquee>';
echo '<a href="http://last.fm/user/' . $uname . '/">';
echo "I'm currently listening to " . $currenttrack . " by " . $artist; // It shows when you're playing music!
echo "</a>";
echo '</marquee>';
}
url不应该有空格,所以你可以把所有的空格都转换成+。因此,您可以直接使用str_replace(" ", "+", $artist)。
同样,你可以使用json_decode来解析json,而不是展开字符串。
PHP parse_url()
php的parse_url函数将非常有用。
<?php
$url = 'http://last.fm/artist/This+Is+A+Band';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH); // will print an array of the different parts of the url you can access with flags
从那里,它只是剥离的东西,你不想通过爆炸的路径返回的组件,获得最后一个项目在你的爆炸数组,并使用str_replace
与参数是在顺序search
, replace
, haystack
的问题
<?php
$url = 'http://last.fm/artist/This+Is+A+Band';
$apiPath = parse_url($url, PHP_URL_PATH));
$parts = explode($apiPath, '/'); // get an array of the path components so you can access the artist
$artist = end($parts); // moves array pointer to last structure
$artist = str_replace(' ','+',$artist); // turn your + into spaces