fagnonk Posted July 10, 2009 Share Posted July 10, 2009 I have a Simple php newbie question about targeting arrays with simpleXML. I have an xml file with nodes that have a whole bunch of attributes attached to them. I know how to target and echo a node but I can't seem to target and echo the the attributes on those nodes. For example, I would like to echo the attribute 'name' on the list node. My xml file looks like this: <?xml version="1.0" encoding="utf-16"?> <!-- http://www.designvillain.com/vp/list1.xml --> <item> <list name="My name" videotitle="My title"> <thumb>1.jpg</thumb> </list> </item> My php looks like this: <?php if( ! $xml = simplexml_load_file('file.xml') ) { echo 'unable to load XML file'; } else { foreach( $xml->list[0]->list as $list ) { echo $list->attributes('name').'<br/>'; } } ?> Any suggestions? Link to comment https://forums.phpfreaks.com/topic/165444-solved-targeting-arrays-with-simplexml/ Share on other sites More sharing options...
Daniel0 Posted July 10, 2009 Share Posted July 10, 2009 foreach ($xml->list as $list) { echo $list['name']; } Here it is implicitly cast as a string because it's used in a printing context, but if you need to do things like comparison you will have to do explicit casting. Link to comment https://forums.phpfreaks.com/topic/165444-solved-targeting-arrays-with-simplexml/#findComment-872603 Share on other sites More sharing options...
fagnonk Posted July 10, 2009 Author Share Posted July 10, 2009 Hmm, still not working. I looked this up in the php reference and it is definitely supposed to work: <?php if( ! $xml = simplexml_load_file('file.xml') ) { echo 'unable to load XML file'; } else { foreach ($xml->list as $list) { echo $list['name']; } ?> Could I still be missing something here? Link to comment https://forums.phpfreaks.com/topic/165444-solved-targeting-arrays-with-simplexml/#findComment-872605 Share on other sites More sharing options...
Daniel0 Posted July 10, 2009 Share Posted July 10, 2009 It works for me. <?php $xml = <<<EOF <?xml version="1.0" encoding="utf-8"?> <!-- http://www.designvillain.com/vp/list1.xml --> <item> <list name="My name" videotitle="My title"> <thumb>1.jpg</thumb> </list> </item> EOF; $xml = simplexml_load_string($xml); foreach ($xml->list as $list) { echo $list['name']; } Outputs: My name Is that not the output you're looking for? Link to comment https://forums.phpfreaks.com/topic/165444-solved-targeting-arrays-with-simplexml/#findComment-872607 Share on other sites More sharing options...
fagnonk Posted July 10, 2009 Author Share Posted July 10, 2009 Ahh I missed a bracket at the end I got it. Thanks! Link to comment https://forums.phpfreaks.com/topic/165444-solved-targeting-arrays-with-simplexml/#findComment-872609 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.