Fetch MP3 Tags from Last.fm Using PHP

Fetch MP3 Tags from Last.fm Using PHP

Today I’m gonna show you a script that I did for a project of mine that fetches the tags from LastFM and updates the database inserting the top 5 tags from their database and leaves your tags as they are.

I believe it could be a lot less messy but I am too lazy to make it more understandable :D You update the tags using yoursite.com/?autotag=id (of the song from your database). You could as easily do a loop and update every song in the database. But why would you :D So let’s go with my messy code!

Ps: you must get your API key on their site.

.

$f = mysql_fetch_assoc(mysql_query('select name, tags from songs where id = "' . $_GET['autotag'] . '"'));
$e = explode('-', $f['name']);
$url = @simplexml_load_file('http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=YOUR API KEY&artist=' . $e[0] . '&track=' . trim($e[1]));
$t_cnt = count($url->track->toptags->tag);
$t = explode(',', $f['tags']);
$tags = array();
for ($i = 0; $i < count($t); $i++) {
    if ($t[$i] != '') $tags[] .= trim($t[$i]);
}
for($j = 0; $j < $t_cnt; $j++) {
    array_push($tags, (string)$url->track->toptags->tag[$j]->name);
}
$tags = array_unique($tags);
$ct = count($tags);
for ($k = 0; $k <= $ct; $k++) {
    if ($tags[$k] != '') $tagss .= ($k >= 1 ? ', ' : '') . $tags[$k];
}
//mysql_query('update songs set tags = "' . $tagss . '" where id = "' . $_GET['autotag'] . '"');
exit($tagss);

It reads the name of the song from the database. The name should be Artist – Title, as it then explodes this at the – and presumes the first piece is the artist and the second is the title of the song. This are the info that LastFM wants you to include in the URL if you want to get the song info.

Next, we read the xml file with the song information. We explode our preexistent tags from the database and we count the tags in the xml file.

We create a new array $tags, which will include our preexistent tags (should be separated by commas (,)). We push our tags into it and then we push the tags from LastFM into it.

We use the array_unique function to delete duplicate tags, if there are any. When we finish doing that, we echo the tags into a new variable, $tagss.

At the end, we could update the database entry (if you uncomment the commented line) or just exit the function and echo our new $tagss variable.

That’s it, hope you understood anything.

Have swing!

If you liked this post think about subscribing to my RSS feed and prevent missing anything interesting. It's free, fast and doesn't hurt. Promise. Click here.
Related posts: