Saving a CSV file to directory can be achieved with the
fopen() function with the correct choice of the many parameters that the function has. In particular, the parameter we are going to use is ‘a’ which instructs PHP to open a new file, creating it if it does not exist and writing to it.
Let’s take a look at the full code snippet that we need to use to create and save the file to a directory.
// Open/Create the file $f = fopen('myCsv.csv', 'a'); // Write to the csv fputcsv($f, ["MyCell1", "MyCell2", "MyCell3"]); // Close the file fclose($f);
Firstly, what is the code doing?
fopen('myCsv.csv', 'a')opens/creates a new file named myCsv.csv in the directory of which the script is executing. This is the important line of code, we will come back to it.
fputcsv($f, ["MyCell1", "MyCell2", "MyCell3"])uses the
$fvariable which allows the function to pass in the array of data or similarly write the data to the file.
fclose($f)closes the file after we’ve finished writing to the file.
So, now we know that
fopen() is responsible for creating and saving the file to a directory, this is the line of code we will focus on.
Let’s use some different scenarios
Create & Save file to the current directory
$f = fopen('myCsv.csv', 'a');
This code will create the file in the directory of the script that is being executed, so if it’s the homepage of your application, the file will be saved in the root directory.
Create & Save file to sub-directory
$f = fopen('myFolder/myCsv.csv', 'a');
This code will save the CSV file to the directory of myFolder/, it is extremely important that the directory you’re trying to save to already exists, otherwise create it before you execute this line. And it is also important to remember that the path you are using as a parameter is always relative to the location of the script too.