File create/write

Creating and writing files in PHP uses the same mechanism as opening them. When you call fopen() with a write (w) or append (a) mode, PHP will create the file if it does not exist.

The important difference is intent: w is destructive and always starts with an empty file, while a preserves everything and adds new content at the end. Writing itself is done with fwrite(), which sends a string into an open file handle and advances the pointer as it writes.

This means you can call fwrite() multiple times in a row and the content will be written sequentially. As with reading, closing the file with fclose() is mandatory, and in WordPress-style code you should always use anchored paths so you know exactly which file you are touching.

The big mental warning here is simple: opening a file in w mode will erase data without asking.