php simplexml - string as object
Hoping somebody can 开发者_如何学Cadvise on an issue I have with simplexml.
I need to specify the paths for various nodes but I'm not sure if this is possible.
$xml = new SimpleXMLElement($xmlstr);
$image1 = 'images->image[0]->image';
foreach ($xml->record as $record) {
echo $record->$image1; // i need this be be recognised as $record->images->image[0]->image
}
Hope this makes sense! Thanks
You can use an array for this:
$xml = new SimpleXMLElement($xmlstr);
$levels = array('images', array('key' => 'image', 'index' => 0), 'image');
foreach ($xml->record as $record) {
$obj = $record;
foreach($levels as $level) {
if(is_array($level))
$obj = $obj->{$level['key']}[$level['index']];
else
$obj = $obj->$level;
}
echo $obj;
}
This builds up the hierarchy by reassigning $obj
equal to itself ->
whatever is next in the array.
PHP cannot interpolate array indices in strings, so if you need to use them, just use an associate array as shown above. :-)
精彩评论