Search code examples
phpsimplexmladdchild

Applying a value to a new XML element with attributes using PHP's simpleXML


Here is a function (in a class that deals with comments) that creates a comment element

function add($id,$message){
    $newcomment = $this->source->addChild('comment');
    $newcomment->addAttribute('user',$id);
    $newcomment->addAttribute('timestamp',time());

    $newcomment = $message; // <--------- fail

    $this->source->asXML($this->save);
    return(true);
}

All of this works but I obviously don't know what I'm doing with the line I'm pointing at. But I basically want to put the message in the comment element like so:

<comments>
  <comment id="12345678" timestamp="1355812061">
    Hey friend, what's up?
  </comment>
  <comment id="87654321" timestamp="1355813155">
    Nothing much, just have this problem with simpleXML
  </comment>
</comments>

But what I have works except that the message isn't set.

So my question is, is this possible and if so, what must I do?


Solution

  • Set the value of the newly created child element with the 2nd parameter to addChild(), like this:

    $newcomment = $this->source->addChild('comment', $message);
    

    Then you can get rid of the line you're pointing to.