Create a .CSV File with PHP

In todays post of the day, I will demonstrate to my readers how to write a CSV file using PHP.

PHP Code to Create a .csv File

Simply copy and paste the following code into your file editor and save it as PHPcsv.php. Note, sometimes when you copy and paste from the web you will have to replace single quotes, double quotes and possible some other characters with basic versions in notepad or another file editor of your choice. If you have problems look for fancy quotes in your file first and replace them with plain ones. Here is the code for PHPcsv.php:

$csv = “ID,Name,Email”.PHP_EOL;//creates 1st line of CSV file with column headings
$csv .= “1,Ian,”.PHP_EOL; //add a few data rows
$csv .= “2,Jafty,”.PHP_EOL;
$csv .= “3,Marc,”.PHP_EOL;
$fname = ‘data.csv’;//give the csv file a name
$fp = fopen($fname,’w’);//open csv file
fwrite($fp,$csv);//write csv data to data.csv
fclose($fp);//close data.csv
echo “<p style=’color:green’>Data written to $fname</p>”;//Let’s us know it is done.

Open the above file in a web browser and you’ll see this in the browser window:
Data written to data.csv

Also, in the directory you uploaded the code to in order to open it in your browser, you will find a new file named data.csv after running the PHPcsv.php script. Yes, the script created the data.csv file as long as you now see the new file in the same directory as PHPcsv.php. Download the file and the contents should look like this when opened in notepad:



Notice the each line of the CSV file is held in the $CSV variable in the code above and ends with PHP_EOL appended to the line. That is the PHP End Of Line constant and it is what keeps your file all nice and organized for you. The PHP_EOL statement basically works as a newline in PHP.



I did leave some things out. The code ultimately should declare the proper headers for CSV file, but this works. If you open it in Excel, it will mention it is not in the proper format, but will open none-the-less and then you can save in the correct format, so this is functional and simple, the way I like things!

Leave a Reply

Your email address will not be published. Required fields are marked *