0

Im trying to parse an XML document using the XPath element in simple XML. However this script below (When searching for the entry "U2" in the last.fm API) returns:

Passengers Passengers Bono Passengers Bono U2 and Green Day Passengers Bono U2 and Green Day R.E.M. Passengers Bono U2 and Green Day R.E.M. INXS

As you can see there are repeating nodes. Is there a way that I can stop duplicate/repeating nodes from being shown?

(PHP Code)

$xmlmusic = new SimpleXMLElement($result);
$releases = $xmlmusic->xpath('artist/similar/artist');
foreach ($releases as $artist) {
$artistResult .= $artist->name . PHP_EOL;
echo $artistResult;}

(XML Document)

<?xml version="1.0" encoding="utf-8"?>
<lfm status="ok">
<artist>
  <name>U2</name>
  <mbid>704acdbb-1415-4782-b0b6-0596b8c55e46</mbid>
  <url>http://www.last.fm/music/U2</url>
  <image size="small">http://userserve-ak.last.fm/serve/34/107345.jpg</image>
  <streamable>1</streamable>
    <stats>
    <listeners>2613654</listeners>
    <playcount>96947986</playcount>
    </stats>

<similar>
  <artist>
  <name>Passengers</name>
  <url>http://www.last.fm/music/Passengers</url>
  <image size="small">http://userserve-ak.last.fm/serve/34/4826014.jpg</image>
  </artist>
Wayne
  • 59,728
  • 15
  • 131
  • 126
MattHeywood
  • 181
  • 1
  • 4
  • 18

1 Answers1

0

I'm assuming that your XML snippet is only a small sample of the full results, so...

you need to modify your foreach loop to check if the artist currently being processed has been seen before. The easiest way is to use an array:

$seen = array();
foreach ($releases as $artist) {
    if (!isset($seen[$artist->name])) {
        $seen[$artist->name] = true;
    }
}

Once the loop's done, you've got a nice array with each artist being a key in $seen. To replicate your simple string concatenation, you simply implode/echo:

echo implode(array_keys(', ', $seen));
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • It wasn't returning any results, so I tried a print of the array: $xmlmusic = new SimpleXMLElement($result); $releases = $xmlmusic->xpath('artist/similar/artist'); $seen = array(); foreach ($releases as $artist) { if (!isset($seen[$artist->name])) { $seen[$artist->name] = true; } } print_r($seen); However its returning an empty array? – MattHeywood Dec 14 '11 at 05:18