Welcome to WebmasterWorld Guest from

Forum Moderators: httpwebwitch

Message Too Old, No Replies

SimpleXML Attributes



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

5+ Year Member

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.


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


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

5+ Year Member

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


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

5+ Year Member

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!

Featured Threads

Hot Threads This Week

Hot Threads This Month