Page 1 of 1

Reading XML root attributes

Posted: Mon Nov 14, 2005 1:43 pm
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 ?

Reading XML root attributes

Posted: Mon Nov 14, 2005 1:58 pm
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

Posted: Mon Nov 14, 2005 4:19 pm
by Ambush Commander

Code: Select all

for ($i = 1; $i < $number_of_attributes; $i++) {
  echo 'att{$i}: ' . $xml['att'.$i];
}

Posted: Mon Nov 14, 2005 4:48 pm
by hawleyjr
michel77: Welcome to the forum.

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