2

I'm getting a xml using the file_get_contents function and then creating a SimpleXMLElement with it.

The xml file can be seen here: http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Nirvana&api_key=0ca5b0824b7973303c361510e7dbfced

The problem is that I need to get the value of lfm->artist->image[@size='small'] and I can't find how to do it.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
ColdFox
  • 61
  • 7
  • This seems to moving in your direction: http://stackoverflow.com/questions/6837479/php-and-xml-looping-through-an-xml-file-with-php – Mr. Concolato Oct 06 '14 at 17:54

1 Answers1

1

You should use DOMXPath for this: http://php.net/manual/en/class.domxpath.php

This XPath query would work for your XML:

\\lfm\artist\image[@size='small']

As follows:

$doc = new DOMDocument();
$doc->loadXML($url);

$xpath = new DOMXpath($doc);

$elements = $xpath->query("\\lfm\artist\image[@size='small']");


if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • XPath is also available from SimpleXMLElement object by using `xpath()` function. See: http://php.net/manual/en/simplexmlelement.xpath.php and yes, this way it's looks like the easiest. – Bartosz Polak Oct 06 '14 at 18:15
  • What am I doing wrong? $requestXML = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=0ca5b0824b7973303c361510e7dbfced&artist=$artist'); $doc = new DOMDocument(); $doc->loadXML($requestXML); $xpath = new DOMXpath($doc); echo $xpath->query("\\lfm\artist\image[@size='small']"); – ColdFox Oct 06 '14 at 18:50
  • Eliminate the `file_get_contents` and `loadXML` lines altogether. Instead use loadHTMLFile() and pass in the XML url. See edited. – AnchovyLegend Oct 06 '14 at 18:53
  • it shows warnings of invalid tag for every xml element in the line with $doc->loadHTMLFile($url); – ColdFox Oct 06 '14 at 19:01
  • See edited, you should use loadXML instead of loadHTML if your loading an XML document. – AnchovyLegend Oct 06 '14 at 19:06
  • Still not working :s "Warning: DOMDocument::loadXML(): Start tag expected, '<' not found in Entity, line: 1" – ColdFox Oct 07 '14 at 08:45
  • Glad to help, please mark as solution if answer was helpful. – AnchovyLegend Oct 07 '14 at 13:55