How can I swap 2 nodes using SimpleXML?
Something like this:
Language: php (GeSHi-highlighted)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>SimpleXML: How to swap nodes</title>
</head>
<body>
<h1>SimpleXML: How to swap nodes</h1>
<?
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Actor</actor>
</character>
</characters>
<plot>
So, this language. It is like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
$xml = new SimpleXMLElement($xmlstr);
$character0 = $xml->movie[0]->characters[0]->character[0];
$character1 = $xml->movie[0]->characters[0]->character[1];
echo "<h2>Character 0</h2><pre>". htmlspecialchars($character0->asXML()) ."</pre>";
echo "<h2>Character 1</h2><pre>". htmlspecialchars($character1->asXML()) ."</pre>";
$xml->movie[0]->characters[0]->character[0] = $character1;
$xml->movie[0]->characters[0]->character[1] = $character0;
echo "<h2>XML</h2><pre>". htmlspecialchars($xml->asXML()) ."</pre>";
?>
<p>The content of the character nodes has vanished!</p>
</body>
</html>
I found a workaround converting to XML string and using stri_replace... ugly but it works and should be solid.
From the comments on the PHP site, il looks like there is no easy way to insert XML into a simpleXML structure:
http://us2.php.net/simplexml#78855The technique described in this comment recursively copies the nodes one by one from one structure to the other... Even uglier than my str_replace method IMHO. Looks like this particular code does not copy the XML attributes, but that could be fixed.
Have I missed something? Is there some magic notation that I should use?
Except for that small detail, SimpleXML is great !
Cheers and thanks in advance for your constructive feedback ;)