我刚开始学习xml,我现在有任务,从php提交的表单中获取数据并将其写入xml文件。我现在在类中有函数,在表单提交后将数据写入xml文件,它看起来像这样
function writeFile () {
$dom = new DomDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
if( $xml = file_get_contents( 'include/users.xml') ) {
$dom->loadXML( $xml, LIBXML_NOBLANKS );
// find the headercontent tag
$users = $dom->getElementsByTagName('users')->item(0);
// добавление корня - <users>
//$users = $dom->appendChild($dom->createElement('users'));
$user = $users->appendChild($dom->createElement('user'));
$xml_name = $user->appendChild($dom->createElement('name'));
$xml_name->appendChild($dom->createTextNode($this->name));
$xml_email = $user->appendChild($dom->createElement('mail'));
$xml_email->appendChild($dom->createTextNode($this->email));
// add the user tag before the first element in the <users> tag
$users->insertBefore( $user, $users->firstChild );
$dom->save('include/users.xml');
}
}
然后在我的users.xml上我有:
<users>
<user>
<name>User1</name>
<mail>new2@mail.ru</mail>
</user>
</users>
但我的问题是我的<user>
数据一直覆盖而不是追加新用户:
<users>
<user>
<name>User1</name>
<mail>new2@gmail.com</mail>
</user>
<user>
<name>User2</name>
<mail>new3@gmail.com</mail>
</user>
</users>
我会感激任何帮助