Lain
Lain

Reputation: 2216

Recursively display nested XML and attributes PHP

The end goal of this is to load an XML Settings file and be able to modify it via html forms. I am having trouble even loading the nested XML with its attributes to print though, which is my first step.

This is a snippit of the XML:

<Settings>
    <GSettings>
        <Name Value="Plane"/>
        <Id Value="50"/>
        <Timeout Value="100"/>
    </GeneralSettings>
    <WingSetting>
        <LeftWing Color="Red" Value="1"/>
        <RightWing Value="0"/>
        <MiddleBar>
            <Fields>
                <Value>Direction</Value>
                <Value>Speed</Value>
                <Value>Height</Value>
            </Fields>
        </MiddleBar>
    </WingSetting>

So the goal for something like this would be to print something along the lines of:

.GSettings.Name = 
ATTRIBUTES:
Value = Plane

.GeneralSettings.Id = 
ATTRIBUTES:
Value = 50

.GeneralSettings.Timeout = 
ATTRIBUTES:
Value = 100

.WingSetting.LeftWing =
ATTRIBUTES:
Value = 1
Color = Red

.WingSetting.RightWing =
ATTRIBUTES:
Value = 0


.WingSetting.MiddleBar=


.WingSetting.MiddleBar.Fields.Value=Direction

.WingSetting.MiddleBar.Fields.Value=Speed

.WingSetting.MiddleBar.Fields.Value=Height

I am able to recursivly print the XML and the children, and in the case of the middlebar fields, I can print the speed direction and height. But I don't know how to get the attributes out and print them as I go. Current code is this:

$xml=simplexml_load_file("MySettings.xml");
RecurseXML($xml);

function RecurseXML($xml,$parent="")
{
   $child_count = 0;
   foreach($xml as $key=>$value)
   {

      $child_count++;    
      if(RecurseXML($value,$parent.".".$key) == 0)  
      {

         echo($parent . "." . (string)$key . " = " . (string)$value . "<BR>\n");       
      }    
   }
   return $child_count;
} 

Which prints it exactly how I want except without the attribute options in it. I know there is an attributes() option but I couldn't figure out how to add it so it does so recursively. Any ideas on how to add this in?

Upvotes: 0

Views: 49

Answers (1)

splash58
splash58

Reputation: 26153

Add this code after echo line

     //  Get an array of attributes
     $attribs = $value->attributes();
     // If its not empty
     if(count($attribs)) {
         echo "ATTRIBUTES:<BR>\n";
     }
     // Output an each attribute value
     foreach($attribs as $k=>$v) {
         echo "$k = $v<BR>\n";
     }

Upvotes: 1

Related Questions