Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding child nodes using SimpleXML
    text
    copied!<p>I have an XML document and want to insert a new node at a specific spot using SimpleXML. </p> <p>The original XML is this:</p> <pre><code>&lt;epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd" &gt; &lt;command&gt; &lt;create&gt; &lt;domain:create xmlns:domain="urn:ietf:params:xml:ns:domain-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:domain-1.0 domain-1.0.xsd" &gt; &lt;domain:period unit="y"&gt;&lt;/domain:period&gt; &lt;/domain:create&gt; &lt;/create&gt; &lt;/command&gt; &lt;/epp&gt; </code></pre> <p>after <code>&lt;domain:create&gt;</code> I need to add the following node:</p> <pre><code>&lt;domain:ns&gt; &lt;domain:hostAttr&gt; &lt;domain:hostName&gt;&lt;/domain:hostName&gt; &lt;domain:hostAddr ip="v4"&gt;&lt;/domain:hostAddr&gt; &lt;/domain:hostAttr&gt; &lt;/domain:ns&gt; </code></pre> <p>How can I do that? I have tried this:</p> <pre><code>$xmlObj = simplexml_load_file('myXMLFile.xml'); $nsNode = $xmlObj-&gt;command-&gt;create-&gt;children(self::OBJ_URI_DOMAIN)-&gt;create-&gt;addChild('domain:ns'); $hostAttr = $nsNode-&gt;addChild('domain:hostAttr'); $hostName = $hostAttr-&gt;addChild('domain:hostName'); $hostAddr = $hostAttr-&gt;addChild('domain:hostAddr'); $hostAddr-&gt;addAtribute('ip', 'v4'); </code></pre> <p>On this first line, I'm getting this warning:</p> <blockquote> <p>Warning: SimpleXMLElement::addChild() [simplexmlelement.addchild]: Cannot add child. Parent is not a permanent member of the XML tree</p> </blockquote> <p>On the second line, and because of this, I'm getting:</p> <blockquote> <p>Fatal error: Call to a member function addChild() on a non-object</p> </blockquote> <p>Thanks in advance.</p> <p>Additional notes: - The php version is higher then 5.1; - I have successfully added child nodes later on this same XML.</p>
 

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