将新帖子添加到XML文件

时间:2011-12-27 18:28:51

标签: php xml simplexml

<?xml version="1.0" encoding="ISO-8859-1"?>
<messages>
<post>
<id>1</id>
<userName>lala</userName>
<text>some nice text</text>
<timePosted>12456754</timePosted>
</post>
</messages>

我想在邮件中添加新帖子,我该怎么办?我尝试用addChild添加它,但没有用。

1 个答案:

答案 0 :(得分:2)

// Load the XML file
$xml = simplexml_load_file($filename);

// Create a new child node
$child = $xml->addChild('post');
$child->addChild('id', $id);
$child->addChild('userName', $username);
$child->addChild('text', $text);
$child->addChild('timePosted', $timeposted);

// Save the updated XML back to the file
$xml->asXML($filename);