Jump to content

Deleting from xml


ozzieing

Recommended Posts

Currently my PHP writes out to an XML document via POST in this kind of format.

<key>User1</key> 
<string>George</string>
<key>User2</key>
<string></string> 
<key>User3</key>
<string>Ryan</string> 

 

But I want to remove the users at certain points. So if George is sent to "Remove.php" via POST then "George" is removed so it then looks like:

<key>User1</key> 
<string></string>
<key>User2</key>
<string></string> 
<key>User3</key>
<string>Ryan</string> 

 

Any help with this? It should be fairly basic but I have no idea where to start. To be honest, I'm a bit of a PHP noob but once this is sorted my application wont need any more PHP.

Link to comment
Share on other sites

<?php

class UserManager {
    protected $_simpleXml;
    
    public function __construct($dataSource {
        $this->_simpleXml = simplexml_load_file($dataSource);
        if (!isset($this->_simpleXml->user)) {
            throw new Exception('Incorrect data source given.');
        }
    }
    
    public function addUser($details) {
        $this->_simpleXml->addChild('key', $details['key']);
        $this->_simpleXml->addChild('string', $details['string']);
    }
    
    public function deleteUser($username) {
        for ($i = 0; $i < $this->_simpleXml->user; $i++) {
            if ($this->_simpleXml->user[$i]->key === $username) {
                unset($this->_simpleXml->user[$i]); break;
            }
        }
    }
    
    public function __toString() {
        return $this->_simpleXml->asXml();
    }
}

$userManager = new UserManager('/path/to/file.xml');
$userManager->deleteUser('User1');
print $userManager;

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.