Parsing XML with PHP?

It made me crazy for the last hour. I'm trying to parse some XML from the Last.fm API, I used about 35 different permutations of the code below, all of which failed. I am very poorly versed in XML analysis, LOL. Can someone help me parse the first toptags> tag> name 'name' from this XML API in PHP ?: (

http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies

In this case ^ will be "electronic"

Right now, all I have is

<? $xmlstr = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies"); $genre = new SimpleXMLElement($xmlstr); echo $genre->lfm->track->toptags->tag->name; ?> 

Returns with an empty. No mistakes either, which is incredibly annoying!

Thank you very much:):):)

Any help is strong, and very strong, I mean really, very grateful! :)

+4
source share
5 answers

The <tag> is an array, so you should skip them with foreach or a similar construct. In your case, just capturing the first will look like this:

 <? $xmlstr = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies"); $genre = new SimpleXMLElement($xmlstr); echo $genre->track->toptags->tag[0]->name; 

Also note that the <lfm> not needed.

UPDATE

It's much easier for me to get exactly what I'm looking for in SimpleXMLElement using print_r() . It will show you what an array is, what a simple string, what another SimpleXMLElement, etc.

+4
source

Try using

 $url = "http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies"; $xml = simplexml_load_file($url); echo $xml->track->toptags->tag[0]->name; 
+2
source

Suggestion: insert the instruction into echo $ xmlstr and make sure you get something back from the API.

+1
source

You do not need to reference lfm . Actually $genre already has lfm . Try the following:

 echo $genre->track->toptags->tag->name; 
+1
source

If you do not want to read the XML data, follow these steps:

$ xmlURL = "your xml url / filename goes here";

 try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $xmlURL); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-type: text/xml' )); $content = curl_exec($ch); $error = curl_error($ch); curl_close($ch); $obj = new SimpleXMLElement($content); echo "<pre>"; var_dump($obj); echo "</pre>"; } catch(Exception $e){ var_dump($e);exit; } 

You will get a formate array of the entire xml file.

Thanks.

0
source

Source: https://habr.com/ru/post/1381711/


All Articles