这是一个创建注释元素的函数(在处理注释的类中)
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);
}
所有这一切都有效,但我显然不知道我正在用我所指的那条线做什么。但我基本上想把消息放在评论元素中,如下所示:
<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>
但是我的工作除了没有设置消息。
所以我的问题是,这是否可行,若然,我该怎么做?
答案 0 :(得分:2)
使用第二个参数将新创建的子元素的值设置为addChild()
,如下所示:
$newcomment = $this->source->addChild('comment', $message);
然后你可以摆脱你指向的那条线。
答案 1 :(得分:1)
所以我的问题是,这是否可行,若然,我该怎么做?
是的,这是可能的。您可以使用数组样式的sytax直接写入元素:
$newcomment[0] = $message;
SimpleXML不允许将文本内容写入普通变量,但它允许写入具有数组样式访问($node[$n] = 'string'
)或属性样式访问($node->child = 'string'
)的元素。
要写入变量中包含的元素,请使用索引0
和数组语法,如上所示。
答案 2 :(得分:0)
创建评论字段时,只需向addChild()
添加第二个参数:
$newcomment = $this->source->addChild('comment', $message);