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
https://forums.phpfreaks.com/topic/165048-deleting-from-xml/
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
https://forums.phpfreaks.com/topic/165048-deleting-from-xml/#findComment-870363
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.