PHP XML添加新条目

How do i edit a xml files and add a new entry at end of < / user > ?

My xml(filezilla) look like

<FileZillaServer>
<Users>
<User Name="test">
</User>
/* using php to add another users on here <User Name="test2" */
</Users>
</FileZillaServer>

Thank you for help.

You can use the DOMDocument classes to manipulate an XML document.

For instance, you could use something like this :

$str = <<<XML
<FileZillaServer>
    <Users>
        <User Name="test">
        </User>
    </Users>
</FileZillaServer>
XML;

$xml = DOMDocument::loadXML($str);
$users = $xml->getElementsByTagName('Users');

$newUser = $xml->createElement('User');
$newUser->setAttribute('name', 'test2');
$users->item($users->length - 1)->appendChild($newUser);

var_dump($xml->saveXML());

Which will get you :

string '<?xml version="1.0"?>
<FileZillaServer>
    <Users>
        <User Name="test">
        </User>
    <User name="test2"/></Users>
</FileZillaServer>
' (length=147)

i.e. you :

  • create a new User element
  • you set its name attribute
  • and you append that new element to Users

(There are probably other ways to do that, avoiding the usage of length ; but this is what I first thought about -- quite early in the morning ^^ )

Use SimpleXML. As the name implies, it's the simplest way to deal with XML documents.

$FileZillaServer = simplexml_load_string(
    '<FileZillaServer>
        <Users>
            <User Name="test" />
        </Users>
    </FileZillaServer>'
);

$User = $FileZillaServer->Users->addChild('User');
$User['Name'] = 'Test2';

echo $FileZillaServer->asXML();