0

Hoping somebody can advise 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

1
  • 1
    Can't you convert it to XPath code? That's a lot easier and more safe to execute than eval()'d PHP code Commented Nov 4, 2010 at 20:11

1 Answer 1

3

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. :-)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.