I have a php-Script, that save some Data into a XML-File. But if two Users save some Data at the same Time, the XML become broken and all Data are lost.
Here is my Code:
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->load($szFile);
... Actions...
$dom->formatOutput = true;
$dom->save($szFile);
Is there a recommend way to save the XML-File without this Problem?
Maybe I must rename the File to be sure no one can acess it?
Open:
function openXML($szFile){
$szPath = '../path/';
$szDummyFile = 'dummy.xml';
$i = 0;
$bRepeat = true;
$bContinue = false;
while($i < 20 && $bRepeat){ // Timeout: 10 s
if(file_exists($szPath . $szFile)){
rename($szPath . $szFile, $szPath . $szDummyFile);
$bRepeat = false;
$bContinue = true;
}else{
usleep(500000); // 0,5 s
}
$i++;
}
if($bContinue){
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->load($szPath . $szDummyFile);
return $dom;
}else{
return false;
}
}
Save:
function saveXML($dom, $szFile){
$szPath = '../path/';
$szDummyFile = 'dummy.xml';
$dom->formatOutput = true;
$dom->save($szPath . $szDummyFile);
rename($szPath . $szDummyFile, $szPath . $szFile);
}