How do you get the object name when using SimpleXML?
If the format is the following, where c is an object array that I must foreach through each iteration:
$a->b->c
And I do:
$z = $a->b
foreach($z as $key => 开发者_开发技巧$value)
echo $value['field'];
$key comes up as null, even though I have valid values. How do I get the name of the object?
XML:
<a>
<b>
<c />
<d />
<e />
</b>
</a>
PHP Code:
$xml = new SimpleXMLElement($file_url, true);
foreach($xml->b->children() as $node) {
echo $node->getName() . "\n";
}
Would give you:
c
d
b
See PHP's manual for further reference.
Considering the following piece of XML and the code to load it with SimpleXML :
$str = <<<XML
<root>
<a>
<b>
<c>glop</c>
<d>test</d>
</b>
</a>
</root>
XML;
$xml = simplexml_load_string($str);
You could "cast" $xml->a->b
to an array, to be able to iterate over it :
foreach ((array)$xml->a->b as $name => $value) {
echo "$name : $value<br />";
}
And you'll get this kind of output :
c : glop
d : test
(maybe not exactly the same XML string as yours, but I hope this will help you get to the solution -- if it does, can you edit your question to show us you XML data, and the output you'll willing to get ? )
Quoting the manual page, at the Converting to array section :
If an object is converted to an array, the result is an array whose elements are the object's properties.
The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.
精彩评论