Read and Print CSV files using php

free php tutorials, php classes, php utilities, free tools

CSV stands for Comma Separated Values. It is a type of file. It means Spreadsheets software like Excel will offer you the opportunity to save files with the CSV extension.

You have data in comma-separated values (CSV) format, for example a file exported from Excel or a database, and you want to extract the records and fields into a format you can manipulate in PHP.

PHP has a function called fgetcsv that allows you to place the values from a csv file into an array. The function reads one line at a time, so it must be placed within a loop in order to process an entire file.


If the CSV data is in a file (or available via a URL), open the file with fopen( ) and read in the data with fgetcsv( ) . This prints out the data in an HTML table:
<?php
// open the text file
$fd = fopen ("animals.csv", "r");
// initialize a loop to go through each line of the file
while (!feof ($fd)) {
$buffer = fgetcsv($fd, 4096); // declare an array to hold all of the contents of each
//row, indexed
echo "n";
// this for loop to traverse thru the data cols
// when this is re-created with MySQL use the mysql_num_fileds() function to get
// this number
for ($i = 0; $i < 5; ++$i){
if ($buffer[$i] == ""){
$buffer[$i] = " ";
}
// print 's with each index
echo "$buffer[$i]n";
}
echo "n";
}
fclose ($fd);
?>

Bookmark This Page