Jump to content

XML Parsing via SimpleXML: nested objects?


the green bandit

Recommended Posts

I'm trying to parse someone else's XML format to read data into php variables.  I'm used to array structures, including nested arrays, but I'm don't understand what's happening here.

 

Sample script:

 

<?php

$string =

'<document>
<table>
<name>Andy</name>
</table>
<table>
<name>Sarah</name>
</table>
<table>
<name>Joe</name>
</table>
</document>';

$xml = simplexml_load_string($string);

var_dump($xml);

?>

 

When run, this returns:

 

object(SimpleXMLElement)#1 (1) { ["table"]=>  array(3) { [ 0]=>  object(SimpleXMLElement)#2 (1) { ["name"]=>  string(4) "Andy" } [1]=>  object(SimpleXMLElement)#3 (1) { ["name"]=>  string(5) "Sarah" } [2]=>  object(SimpleXMLElement)#4 (1) { ["name"]=>  string(3) "Joe" } } }

 

 

Basically, I'd just like to be able to access these properties.  ie, the equivalent (using array notation) of print $xml[0]['name']; .

 

I don't understand why the var_dump is returning what looks like multiple SimpleXML objects (ie, #1, #2, #3, #4).

 

I've tried using a foreach loop to iterate through values, as in:

 

foreach ($xml as $value)

{
print '<br>';

var_dump($xml -> $value);
}

 

Which returns empty objects:

 

object(SimpleXMLElement)#7 (0) { }

object(SimpleXMLElement)#6 (0) { }

object(SimpleXMLElement)#7 (0) { }

 

I've been able to parse XML using other methods, but this has me completely stumped.  Any explanations or directions to helpful resources would be much appreciated.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.