This article demonstrates how to print an array to a file in PHP.

1. Using file_put_contents() function

You can use the file_put_contents() function to write contents to a file. The idea is to get a string representation of the array and then write it to the file. The following solution uses the var_export() function to get the parsable string representation of a variable. The second parameter of var_export() is set to true to return the string representation instead of printing it.

Download Code

 
Note that if the file already exists, it is overwritten. To append the data to the file instead of overwriting it, you can set the FILE_APPEND flag. For example, the following solution uses the FILE_APPEND mode to append the array representation to the end of the file. It is recommended to use the LOCK_EX flag to acquire a write lock on the file. This will avoid any outside modification to the file at the same time of the file_put_contents() update.

Download Code

 
You can also use the print_r() function to get the string representation of the array. The idea remains similar: capture the output of print_r() by setting the return parameter to true. Then, save the data to a file with the file_put_contents() function.

Download Code

2. Using fwrite() function

You may also successively call fopen(), fwrite(), and fclose() to write data to a file. This approach works in the same way as the file_put_contents() function. The following code provides an illustration using the var_export() function.

Download Code

 
The 'w' mode opens the file for writing. The file is created if it does not exist, otherwise, it gets truncated to length zero. To append the data instead of overwriting the file, you can open the stream in append mode 'a'. To acquire an exclusive lock, you can use the flock() function.

The following solution opens a file in append mode and acquires an exclusive lock. Then it writes the array contents to the file and flushes the output before releasing the lock.

Download Code

That’s all there is to printing an array to a file in PHP.