Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>SimpleXML doesn't support that kind of manipulation. Currently, it can only append children. To insert children at arbitrary places in the tree, you need <a href="http://docs.php.net/manual/en/book.dom.php" rel="nofollow noreferrer">DOM</a> and <a href="http://docs.php.net/manual/en/domnode.insertbefore.php" rel="nofollow noreferrer">DOMNode::insertBefore()</a> specifically. The problem is that DOM is verbose and it makes it annoying to use, that's why when I have to do that kind of things, I use a mixture of SimpleXML and DOM. The result became a library aptly named <a href="http://code.google.com/p/simpledom/" rel="nofollow noreferrer">SimpleDOM: use DOM methods with SimpleXML grammar</a>.</p> <p>Also, here's a few tips that I recommend as good practice:</p> <ul> <li>Whenever you create a SimpleXMLElement object, name it after the node it represents. Never name it <code>$xml</code>. "XML" is a markup language, it's text. If I'd see an <code>$xml</code> var I'd think it contains text.</li> <li>The same applies to your <code>$xml_toload</code> var. It doesn't contain XML, it contains a filepath. Therefore, it should be named something like <code>$filepath</code>.</li> <li>You don't have to use <code>addAttribute()</code> or <code>addChild()</code> for everything. It's often simpler to use the array notation and/or the object notation.</li> </ul> <p>The result script:</p> <pre><code>include 'SimpleDOM.php'; // create an &lt;image/&gt; element $image = new SimpleXMLElement('&lt;image/&gt;'); $image['imageURL'] = $file; $image['thumbURL'] = $file; $image['linkURL'] = $linkurl; $image['linkTarget'] = $linkurl; $image-&gt;caption = $caption; // load the file $path_to_file = $_SERVER['DOCUMENT_ROOT']. '/xml/'.$country.'/compact.xml'; $imagegallery = simpledom_load_file($path_to_file); // insert the new element before the first &lt;image/&gt; $imagegallery-&gt;insertBefore($image, $imagegallery-&gt;image[0]); // save the file $imagegallery-&gt;asXML($path_to_file); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload