pb_
pb_

Reputation: 492

Tags appended at the end of xml file

I have an xml file with the following format-

<?xml version="1.0"?>
<db>
<count></count>
<uid></uid>
<score></score>
</db>

I am adding thousands of items to my xml file.

I am using simplexml in php to parse my xml. I am opening an xml file like this-

$result= new SimpleXMLElement($file, null, true);

and closing it like this-

file_put_contents($file, $data->asXML()); 

While everything is working perfectly when I am running this on my localserver, but when I upload this online on my server, it works alright for sometime, and after some time, this gets appended at the end of my xml file

<?xml version="1.0"?>
<db>
<count></count>
<uid></uid>
<score></score>
</db>
/score></db>

and I get a parsing error-

unwanted data appended at the end of xml file

I am confused what is wrong, as it works perfectly fine on my localserver. IS it my code's fault or the server's?

Edit: The count, uid and score are pre populated. I am only updating the score. Here is the code for updating score part-

$data= new SimpleXMLElement($file, null, true);
$winner=intval($data->score[$winid]);
$loser=intval($data->score[$loseid]);
$exp_winner=expected($loser,$winner);
$new_win=win($winner,$exp_winner);
$exp_loser=expected($winner,$loser);
$new_lose=loss($loser,$exp_loser);
$data->score[$winid]=$new_win;
$data->score[$loseid]==$new_lose;
file_put_contents($file, $data->asXML());

Upvotes: 0

Views: 73

Answers (1)

IMSoP
IMSoP

Reputation: 97718

Although it's not made very explicit on the manual page, it seems that the default behaviour of file_put_contents is not to lock the file being written. This could mean that two PHP processes both try to overwrite the file at the same time, which may be the cause of your corruption.

To eliminate this possibility, you can pass the LOCK_EX flag as a third parameter, i.e. file_put_contents($file, $data->asXML(), LOCK_EX);

(I'm not sure how to test this hypothesis, since it seems likely to be a rare race condition you are encountering...)

Upvotes: 1

Related Questions