I have an xml file populated with keys and once a particular key has been used it will be deleted from the xml file. The code below runs, but does not delete the key from the xml file. I’ve read here on SO that maybe putting an “&” in the foreach() will ensure that I’m working with the actual xml file data rather than the temporary data created by the foreach(), but all I get when I run this code is;
Fatal error: An iterator cannot be used with foreach by reference in ....
xml file
<proctor>
<keys>
<key>afvr3e</key>
<key>578jyd</key>
<key>hnr6rg</key>
<key>890kg7</key>
<key>hn3rgd</key>
</keys>
</proctor>
php index file
$key = new ProctorKey('proctorKey.xml');
$key->DeleteKey('hnr6rg');
php class file
class ProctorKey
{
private $file;
public function __construct($file)
{
$this->file = $file;
}
public function DeleteKey($keyToDelete)
{
$xml = simplexml_load_file($this->file)or die("Error: Cannot create object");
/* this throws a fatal error
* foreach($xml->keys as &key)
*/
foreach($xml->keys->key as $key)
{
if($key==$keyToDelete)
{
unset($key);
print('found');
}
}
return $this->FormatXML($xml->asXML());
}
private function FormatXML($data)
{
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($data);
$dom->save($this->file);
$response = ($dom)?true:false;
return $response;
}
}
The snippet below helps in two keys ways:
keyelement(s) that you wish to deleteunseton the actual element rather than the$keyvariable (it’s a quirk ofSimpleXMLElementbeing an iterable object too).Snippet