Jump to content

simpleXMLElement attribute parsing.


DIM3NSION

Recommended Posts

I have a simpleXMLelement and the element objects in the array have the attribute [type]. This distinguishes them from each other. How would i go about parsing the objects that just have the attribute type set to [type] => release and displaying the summary section of that object.

 

below is an simpleXMLelement object code as an example

 

    [6] => SimpleXMLElement Object

                        (

                            [@attributes] => Array

                                (

                                    [num] => 7

                                    [type] => master

                                )

 

                            [title] => DJ Tiësto - Sparkles

                            [uri] => http://www.discogs.com/DJ-Tiësto-Sparkles/master/4001

                            [summary] => DJ Tiësto Sparkles Electronic Trance 1999  Sparkles (Airscape Remix) Sparkles (Original) Sparkles

                        )

 

 

 

 

and this is the PHP that creates the element -

 

 

$xmlmusic = new SimpleXMLElement($result);

 

Thanks guys.

DIM3NSION  :D

 

Link to comment
https://forums.phpfreaks.com/topic/235382-simplexmlelement-attribute-parsing/
Share on other sites

This is one of the somewhat annoying things about simplexml, but you need to call attributes() on the node, and it returns you an associative array with the keys being the attribute names.  You also have to cast it to whatever variable type it should be in most cases.  I'll do something like this:

 

$t = $xmlmusic->nodename->attributes();
echo (string)$t['type'];

 

 

Would i have to do a foreach loop on that?

 

foreach ($xmlmusic as $xm)

    {

        $attrs = $xm->attributes();

        if($attrs['type'] == "release")

            echo $xm->summary."\n";

    }

 

Ive tried this but with no luck. Is there anything wrong with that code?

 

Thanks for your help,

 

DIM3NSION

It might make more sense to use an XPath query to ask for only the type="release" results.

 

$releases = $xmlmusic->xpath('searchresults/result[@type="release"]');
foreach ($releases as $release) {
echo $release->summary . PHP_EOL;
}

 

P.S. The above is based on using the Discogs API, which it looks like you're using.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.