Can this fopen code be improved
I'm seeing that this code first creates the file, closes it, then opens it with 'a'
, writes to it, then closes it. Is there a way to simplify it. The idea is that if t开发者_JAVA百科he file name exists, it needs to be overwritten. I also don't understand the point of unset
. Is it necessary?
$fp = fopen($file_name, 'w');
fclose($fp);
unset($fp);
$fp = fopen($file_name, 'a');
fputs($fp, "sometext");
fclose($fp);
unset($fp);
From php.net, under the 'w' mode in fopen: Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
In other words, open for writing, and overwrite or create as necessary. No need to use append mode.
$fp = fopen($file_name, 'w');
fputs($fp, "sometext");
fclose($fp);
file_put_contents($file_name, 'sometext');
And, No, unset()
is pointless in your case.
精彩评论