Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The xml_adopt() example doesn't preserve namespace nodes.<br> My edit was rejected because it changed to much? was spam?.</p> <p>Here is a version of xml_adopt() that preserves namespaces.</p> <pre><code>function xml_adopt($root, $new, $namespace = null) { // first add the new node // NOTE: addChild does NOT escape "&amp;" ampersands in (string)$new !!! // replace them or use htmlspecialchars(). see addchild docs comments. $node = $root-&gt;addChild($new-&gt;getName(), (string) $new, $namespace); // add any attributes for the new node foreach($new-&gt;attributes() as $attr =&gt; $value) { $node-&gt;addAttribute($attr, $value); } // get all namespaces, include a blank one $namespaces = array_merge(array(null), $new-&gt;getNameSpaces(true)); // add any child nodes, including optional namespace foreach($namespaces as $space) { foreach ($new-&gt;children($space) as $child) { xml_adopt($node, $child, $space); } } } </code></pre> <p>(edit: example added)</p> <pre><code>$xml = new SimpleXMLElement( '&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"&gt; &lt;channel&gt;&lt;/channel&gt;&lt;/rss&gt;'); $item = new SimpleXMLElement( '&lt;item xmlns:media="http://search.yahoo.com/mrss/"&gt; &lt;title&gt;Slide Title&lt;/title&gt; &lt;description&gt;Some description&lt;/description&gt; &lt;link&gt;http://example.com/img/image.jpg&lt;/link&gt; &lt;guid isPermaLink="false"&gt;A1234&lt;/guid&gt; &lt;media:content url="http://example.com/img/image.jpg" medium="image" duration="15"&gt; &lt;/media:content&gt; &lt;/item&gt;'); $channel = $xml-&gt;channel; xml_adopt($channel, $item); // output: // Note that the namespace is (correctly) only preserved on the root element '&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0"&gt; &lt;channel&gt; &lt;item&gt; &lt;title&gt;Slide Title&lt;/title&gt; &lt;description&gt;Some description&lt;/description&gt; &lt;link&gt;http://example.com/img/image.jpg&lt;/link&gt; &lt;guid isPermaLink="false"&gt;A1234&lt;/guid&gt; &lt;media:content url="http://example.com/img/image.jpg" medium="image" duration="15"&gt; &lt;/media:content&gt; &lt;/item&gt; &lt;/channel&gt; &lt;/rss&gt;' </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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