PHP / Programmings

Extract Data From CSV or Excel File in PHP

You can extract csv files easier  than excel(.xls) files using php. I think easier way to extract data from excel file is save file as csv ,then extract and use data according to your needs.

The following code demonstrates the extraction of csv file ‘test.csv‘ in the same directory. The php function fgetcsv($handle,$length,$separator) fetch the fields row by row, where $handle is the file resource, $length is the limiting characters of the fields and the $separator separates the fields,here “,” because of coma separated values (csv file).

<?php
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { //fetch fields row by row from csv 
$num = count($data);                                      //number of fields in each row
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";                              //prints each fields(data)
}
}
fclose($handle);
}
?>

Now you can perform any operations on extracted data like db insertion, updation etc.

If you want to fetch data directly from Excel, go for PHPExcel, A project providing set of classes for php, which allow you to write to and read from different spreadsheet file formats, like Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML, …
Click here to go to PHPExcel Home page

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s