I’m trying to swap all attribute id’s at once from ‘$old’ > ‘$new’ then save the xml:
$reorder = array( 9=>"8", 8=>"5", 7=>"4", 6=>"3", 5=>"0", 4=>"1", 3=>"9", 2=>"7", 1=>"2", 0=>"6" );
$objDOM = new SimpleXMLElement(some.xml, null, true);
foreach ($reorder as $old => $new) {
$picture = $objDOM->xpath('picture[@id="'.$old.'"]');
$picture[0]["id"] = $new;
}
echo $objDOM->asXML();
The result below (doesn’t match Array $reorder)
- 3 > 9
- 9 > 6
- 8 > 8
- 7 > 2
- 6 > 3
- 5 > 5
- 4 > 4
- 0 > 0
- 1 > 1
- 7 > 2
It seems to be switching the id’s in sequence, so id’s that have just been switched are then switched again if they come up later in the array.
What I’m doing wrong there? How can I get it to switch ALL the id’s in one go?
Thanks…
Andy
The answer are two loops
fist you search the xpath for the old id, store it in an array
and then loop again to replace the stored results with the new id
Output:
to save an array you could use
array_popto get the last occurrence of picture@id=xy.which should be the wanted one (read comments for drawbacks)