homepage Welcome to WebmasterWorld Guest from 54.161.214.221
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / XML Development
Forum Library, Charter, Moderators: httpwebwitch

XML Development Forum

    
SimpleXML Attributes
webfoo




msg:4221003
 6:06 pm on Oct 23, 2010 (gmt 0)

What is the easiest way to access an attribute of an XML element with Simple XML?

I am trying to output a simple list of members and their ID's. data.xml's 4th level element is <members>. Within that, there is a <member id="X">John Doe</member> for each member. So far, the code below only lists the name of the member, not their ID.

$xml=simplexml_load_file("data.xml");

foreach($xml->children()->children()->children()->children() as $membercontainer) {
foreach($membercontainer->children() as $member) {
echo "Name=".$member;
echo " ID=" . $member->attributes('id');
echo "<br />";
}
}

 

astupidname




msg:4221183
 5:08 am on Oct 24, 2010 (gmt 0)

$member['id'] will get you there, also:
$attrs = $member->attributes(); $id = $attrs['id'];
Or even:
$id = $member->attributes()->id;

webfoo




msg:4221307
 4:50 pm on Oct 24, 2010 (gmt 0)

Aha. Turns out to me a stupid mistake on my part (as usual).

I mis-read the structure of data.xml. The actual structure of the XML file is as follows:
<member id="X"><name>John Doe</name></member>

The code I wrote grabbed <name>'s attributes rather than <member>'s attributes. <name> does not have any attributes, so it is no wonder that no values were being returned.

For the record, the corrected code is:

foreach($xml->children()->children()->children()->children() as $members) {
foreach($members->children() as $member) {
print ("Name=" . $member);
echo " =" . $members['id'];
echo "<br />";
}
}


Thank you for your help anyways!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / XML Development
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved