title: How do I dynamically create a PHP SimpleXMLElement Object while keeping current properties?
body: <p>I am reading in a an xml file which returns me a SimpleXMLElement Object representation of the xml. I am going to take an array and feed in new values to that object. I don't know what I am going to be in that array.</p>
  
  <p>if I were to brute force this I would do something like this.</p>
  
  <pre><code>//Solution 1: Brute Force
  
      //Just creating an array and value for purposes of demonstration.
      $arOfData = array( [0]=&gt;"theFirstNode", [1]=&gt;"theSecondNode",[2]=&gt;"theThirdNode" );
      $value = "The XML Node Value";
  
      $simpleXml-&gt;$arOfData[0]-&gt;$arOfData[1]-&gt;$arOfData[2] = $value;
  
      //The next best thing I can think of doing is something like this.
      //Solution 2: Semi-brute force
      //
      foreach($this-&gt;arrayData as $key =&gt; $value) {
                  $xmlNodes = explode( '-', $key);
                  $numNodes = count($xmlNodes);
                  switch($numNodes) {
                      case 1:
                          $simpleXml-&gt;$xmlNodes[0] = $value;
                          break;
                      case 2:
                          $simpleXml-&gt;$xmlNodes[0]-&gt;$xmlNodes[1] = $value;
                          break;
                      case 3:
                          $simpleXml-&gt;$xmlNodes[0]-&gt;$xmlNodes[1]-&gt;$xmlNodes[2] = $value;
                          break;
                      case 4:
                          $simpleXml-&gt;$xmlNodes[0]-&gt;$xmlNodes[1]-&gt;$xmlNodes[2]-&gt;$xmlNodes[3] = $value;
                          break;
                      case 5:
                          $simpleXml-&gt;$xmlNodes[0]-&gt;$xmlNodes[1]-&gt;$xmlNodes[2]-&gt;$xmlNodes[3]-&gt;$xmlNodes[4] = $value;
                          break;
                  }
              }
  </code></pre>
  
  <p>*note This solution uses the array key and explodes it to an array delimited by a dash and then uses the array value as the new xml value. So don't let that distract you.</p>
  
  <p>The problem with solution #2 is: what happens when we get a xml node that is deeper than 5? Its not going to be stuffed into our new object we are creating. Oh oh. It's also not very elegant ;). I am not sure how to do this in a more recursive manner.</p>