Here is the XML:
<Routes>
<Route type="source">
<Table>
<Tablename>incoming</Tablename>
<Fields>
<Fieldsname ref="description" name="Route Name">description</Fieldsname>
<Fieldsname name="CID Match">cidnum</Fieldsname>
<Fieldsname name="DID Match">extension</Fieldsname>
<Fieldsname ref="dest">destination</Fieldsname>
</Fields>
</Table>
</Route>
</Routes>
Then my instantiation of it in PHP:
$doc = new SimpleXMLElement('routingConfig.xml', null, true);
print_r($doc->Route[0]) shows this:
SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => source
)
[comment] => SimpleXMLElement Object
(
)
[Table] => SimpleXMLElement Object
(
[Tablename] => incoming
[comment] => SimpleXMLElement Object
(
)
[Fields] => SimpleXMLElement Object
(
[Fieldsname] => Array
(
[0] => description
[1] => cidnum
[2] => extension
[3] => destination
)
[comment] => Array
(
[0] => SimpleXMLElement Object
(
)
[1] => SimpleXMLElement Object
(
)
)
)
)
)
Notice how the root value has the @attributes array. Why doesn’t $doc->Routes[0]->Table->Fields->Fieldsname have @attributes? I realize I can get it via attributes(), but is there a way to make it be included in $doc?
EDIT
Apparently print_r() doesn’t display every value in the array/object, exploring all children etc. Or perhaps SimpleXMLElement doesn’t return it unless requested (seems like it should all be stored in $doc). If you do print_r($doc->Route[0]->Table->Fields->Fieldsname[0]);, it returns
SimpleXMLElement Object
(
[@attributes] => Array
(
[ref] => description
[name] => Route Name
)
[0] => description
)
Which shows the data I am looking for. But if I do a print_r($doc->Route[0]->Table->Field); the data does not appear.
The
SimpleXMLElementobject does some very advanced things in PHP. It implements a lot of the “magic” hooks that PHP provides so that it works in things likeforeach()and is meant to be treated like a “black box”. So because of that, usingprint_r()on it will give you misleading and incomplete information. You just can’t rely onprint_r()(orvar_dump()) on aSimpleXMLElementobject.The way to debug the structure in a
SimpleXMLElementis to simply look for the elements you’re after: things likeisset($xmlnode->child)work, for instance. Sois_array($doc->Route[0]->Table->Fields->Fieldsname)will be true.