Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I set text value of SimpleXmlElement without using its parent?
    text
    copied!<p>I want to set text of some node found by xpath() </p> <pre><code>&lt;?php $args = new SimpleXmlElement( &lt;&lt;&lt;XML &lt;a&gt; &lt;b&gt; &lt;c&gt;text&lt;/c&gt; &lt;c&gt;stuff&lt;/c&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt;code&lt;/c&gt; &lt;/d&gt; &lt;/a&gt; XML ); // I want to set text of some node found by xpath // Let's take (//c) for example // convoluted and I can't be sure I'm setting right node $firstC = reset($args-&gt;xpath("//c[1]/parent::*")); $firstC-&gt;c[0] = "test 1"; // like here: Found node is not actually third in its parent. $firstC = reset($args-&gt;xpath("(//c)[3]/parent::*")); $firstC-&gt;c[2] = "test 2"; // following won't work for obvious reasons, // some setText() method would be perfect but I can't find nothing similar, $firstC = reset($args-&gt;xpath("//c[1]")); $firstC = "test"; // maybe there's some hack for it? $firstC = reset($args-&gt;xpath("//c[1]")); $firstC-&gt;{"."} = "test"; // nope, just adds child named . $firstC-&gt;{""} = "test"; // still not right, 'Cannot write or create unnamed element' $firstC["."] = "test"; // still no luck, adds attribute named . $firstC[""] = "test"; // still no luck, 'Cannot write or create unnamed attribute' $firstC-&gt;addChild('','test'); // grr, 'SimpleXMLElement::addChild(): Element name is required' $firstC-&gt;addChild('.','test'); // just adds another child with name . echo $args-&gt;asXML(); // it outputs: // // PHP Warning: main(): Cannot add element c number 2 when only 1 such elements exist // PHP Warning: main(): Cannot write or create unnamed element // PHP Warning: main(): Cannot write or create unnamed attribute // PHP Warning: SimpleXMLElement::addChild(): Element name is required // &lt;?xml version="1.0"? &gt; // &lt;a&gt; // &lt;b&gt; // &lt;c .="test"&gt;test 1&lt;.&gt;test&lt;/.&gt;&lt;.&gt;test&lt;/.&gt;&lt;/c&gt; // &lt;c&gt;stuff&lt;/c&gt; // &lt;/b&gt; // &lt;d&gt; // &lt;c&gt;code&lt;/c&gt; // &lt;c&gt;test 2&lt;/c&gt;&lt;/d&gt; // &lt;/a&gt; </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