How can fopen() be used in PHP to open a file for writing and what are the implications of using different modes like "w" and "a"?
To open a file for writing in PHP using fopen(), you can use modes like "w" (write only) or "a" (append only). "w" mode will create a new file or truncate an existing file to zero length, while "a" mode will append data to the end of the file without truncating it. It's important to be cautious when using "w" mode as it can overwrite existing data in the file.
// Open a file for writing using "w" mode
$file = fopen("example.txt", "w");
// Check if the file opened successfully
if ($file) {
// Write data to the file
fwrite($file, "Hello, World!");
// Close the file
fclose($file);
} else {
echo "Failed to open the file for writing.";
}