Question

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?

Was it helpful?

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.

OTHER TIPS

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

Yes, this is possible. You can write to the element directly using the array-style sytax:

$newcomment[0] = $message;

SimpleXML does not allow writing text content to a plain variable, but it does allow writing to an element with array-style access ($node[$n] = 'string') or property-style access ($node->child = 'string').

To write to the element contained in the variable, use index 0 with the array syntax as shown above.

Just add a second parameter to addChild() when creating the comment field:

$newcomment = $this->source->addChild('comment', $message);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top