0

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.

2 Answers 2

1

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 ^^ )

Sign up to request clarification or add additional context in comments.

Comments

0

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();

2 Comments

It append <User Name="Test2"/></Users> notice the / after "test2", it shouldn't be there.
It very much must be there, I can assure you. Otherwise, your XML would be malformed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.