Reading XML root attributes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
michel77
Forum Newbie
Posts: 17
Joined: Sun Nov 06, 2005 4:57 am

Reading XML root attributes

Post by michel77 »

Code: Select all

$string = <<<XML
<firstlevel att1="yellow" att2="green">
<secondlevel> ...</secondlevel>
</firstlevel>
XML;

$xml =simplexml_load_string($string);
foreach($xml->firstlevel[0]->attributes() as $a => $b) //doesn't work
{echo $a,'="',$b,"\"\n";}
How to read the attributes att1 , att2 ?
michel77
Forum Newbie
Posts: 17
Joined: Sun Nov 06, 2005 4:57 am

Reading XML root attributes

Post by michel77 »

There is a solution:

Code: Select all

echo 'att1: ' . $xml['att1'];
echo 'att2: ' . $xml['att2'];
But I have to know the names of attributes and in case moroe than 10 attributes to much to write
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Code: Select all

for ($i = 1; $i < $number_of_attributes; $i++) {
  echo 'att{$i}: ' . $xml['att'.$i];
}
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

michel77: Welcome to the forum.

Please take a minute and read the following thread on Posting Code in the Forums
Post Reply