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.

1

1 Answer 1

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";
    }
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

XPath is also available from SimpleXMLElement object by using xpath() function. See: php.net/manual/en/simplexmlelement.xpath.php and yes, this way it's looks like the easiest.
What am I doing wrong? $requestXML = file_get_contents('ws.audioscrobbler.com/2.0/…); $doc = new DOMDocument(); $doc->loadXML($requestXML); $xpath = new DOMXpath($doc); echo $xpath->query("\\lfm\artist\image[@size='small']");
Eliminate the file_get_contents and loadXML lines altogether. Instead use loadHTMLFile() and pass in the XML url. See edited.
it shows warnings of invalid tag for every xml element in the line with $doc->loadHTMLFile($url);
See edited, you should use loadXML instead of loadHTML if your loading an XML document.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.