What are the potential issues with using fopen("a") in a foreach loop when working with flatfile databases in PHP?

Using fopen("a") in a foreach loop to open and write to a file can lead to performance issues and potential file corruption if multiple processes try to write to the file simultaneously. To solve this issue, it is recommended to open the file outside of the loop, write to it within the loop, and then close the file after the loop has finished.

$file = fopen("data.txt", "a");

foreach ($data as $item) {
    fwrite($file, $item . PHP_EOL);
}

fclose($file);