php read csv file
In this article, I will be showing you how to read and write CSV file with PHP.
I have used PHP function fgetcsv to read CSV fields and fputcsv to write on CSV file.
fgetcsv — Gets line from file pointer and parse for CSV fields.
fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
This works on PHP 4 and PHP 5.
fputcsv — Format line as CSV and write to file pointer.
fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.
This works on PHP 5 or greater.
Read CSV file
The following code reads data from a CSV file read.csv and displays in tabular form.
<?php $row = 1; if (( $handle = fopen ( "read.csv" , "r" )) !== FALSE) { ?> <table border= '0' cellpadding= "4" cellspacing= "1" > <?php while (( $data = fgetcsv ( $handle , 1000, "," )) !== FALSE) { $num = count ( $data ); ?> <tr <?php if ( $row ==1){ echo "style='font-weight:bold; background-color:#CCCCCC'" ;} else { echo "style='background-color:#DDDDDD'" ;} ?> style= "background-color:#DDDDDD" > <?php for ( $c =0; $c < $num ; $c ++) { ?> <td><?php echo $data [ $c ]; ?></td> <?php } ?> </tr> <?php $row ++; } fclose( $handle ); ?> </table> <?php } ?> |
Write CSV file
The following code writes data to a CSV file file.csv. The data will be in the form of array. Each element will be the row of CSV file. The element of array is in comma separated form.
<?php $list = array ( 'aaa,bbb,ccc,dddd' , '123,456,789' , '"aaa","bbb"' ); $fp = fopen ( 'file.csv' , 'w' ); foreach ( $list as $line ) { fputcsv ( $fp , split( ',' , $line )); } fclose( $fp ); echo "CSV File Written Successfully!" ; ?> |
Read from one CSV file and write into the other
The following code read data from a CSV file read.csv and writes the same data to another CSV file readwirte.csv
<?php // open the csv file in write mode $fp = fopen ( 'readwrite.csv' , 'w' ); // read csv file if (( $handle = fopen ( "read.csv" , "r" )) !== FALSE) { while (( $data = fgetcsv ( $handle , 1000, "," )) !== FALSE) { // write csv file fputcsv ( $fp , $data ); } fclose( $handle ); fclose( $fp ); echo "CSV File Written Successfully!" ; } ?> |
Hope this helps. Thanks.
From Mukesh Chapagain's Blog, post PHP: Read Write CSV