0

Hello guys im trying to get info from last.fm, i'm getting albums names and etc, but i want to get from line 2. how to get it?

<topalbums artist="Adele" page="1" perPage="1" totalPages="55092" total="55092">

^from here name, page, perpage and totalpages

<lfm status="ok">
<topalbums artist="Adele" page="1" perPage="1" totalPages="55092" total="55092">
<album>

<name>21</name>
<playcount>52308837</playcount>
<mbid>c45e0e0e-48c9-4441-aac3-2f2b34202d3c</mbid>
<url>https://www.last.fm/music/Adele/21</url>
<artist>

<name>Adele</name>
<mbid>cc2c9c3c-b7bc-4b8b-84d8-4fbd8779e493</mbid>
<url>https://www.last.fm/music/Adele</url>
</artist>
<image size="small">
https://lastfm-img2.akamaized.net/i/u/34s/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
<image size="medium">
https://lastfm-img2.akamaized.net/i/u/64s/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
<image size="large">
https://lastfm-img2.akamaized.net/i/u/174s/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
<image size="extralarge">
https://lastfm-img2.akamaized.net/i/u/300x300/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
</album>
</topalbums>
</lfm>
L. P.
  • 113
  • 11

3 Answers3

1
$dom = new DOMDocument();
$dom->loadXML($xml);
$topAlbums = $dom->getElementsByTagName('topalbums')->item(0);
$artist = $topAlbums->getAttribute('artist');
echo $artist; // outputs Adele
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
0

One basic way would be to use a regular expression:

preg_match('/artist="([^"]*)"\\s*page="([^"]*)"\\s*perPage="([^"]*)"\\s*totalPages="([^"]*)"/', $lastfm_input, $result);
# $result[1] = name value
# $result[2] = page value
# $result[3] = perPage value
# $result[4] = totalPages value

If the order of the attributes (like perPage) changes you have to use multiple regexes.

A Person
  • 1,062
  • 9
  • 17
  • No, completely wrong. Regex should never parse HTML or XML, there's a famous Stack Overflow post about this, look it up. – delboy1978uk Apr 18 '17 at 08:42
  • I agree that it is better to use a parser, I just wanted to present this option aswell. (Because there is always more than one way to do it and it might help someone with another but similar problem.) Do you have the link to the post you mentioned? – A Person Apr 18 '17 at 08:48
  • Certainly - enjoy! :-D http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – delboy1978uk Apr 18 '17 at 08:54
  • Very nice! :D I think the second highest voted answer to that question explains why I don't have a problem with some regexes that are used to casually extract some data out of a XML string. :) – A Person Apr 18 '17 at 09:06
-1

Guys funnily i found best solution

<?php 
$attrs = $xml7->topalbums->attributes();
echo $attrs["total"];
?>
L. P.
  • 113
  • 11