Wednesday, January 30, 2013

Read and Write CSV File In PHP


Read and Write CSV File  


comma-separated values (CSV) file stores tabular data (numbers and text) in plain-text form. Plain text means that the file is a sequence of characters, with no data that has to be interpreted instead, as binary numbers. A CSV file consists of any number of records, separated by line breaks of some kind; each record consists of fields, separated by some other character or string, most commonly a literal comma or tab. Usually, all records have an identical sequence of fields.

So First we will see the structure of an CSV file.

one, two

example1, example2
data1, data2
test1, test2

now first we see how to read from a CSV file, here we go we will use php function "fgetcsv" it will read the content of csv file as given in example

<?php

function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}

// Set path to CSV file

$csvFile = 'test_data.csv';

//calling the function

$csv = readCSV($csvFile);
if(!empty($csv)){
    foreach($csv as $file){
        //inserting into database
        $query_insert = "insert into csv_data_upload set 
            name    =   '".$file[0]."',
            value   =   '".$file[1]."'";
            echo $query_insert;
        $insert = mysql_query($query_insert);   
  }
}else{
   echo 'Csv is empty'; 
    
}

?>



On executing this code the data will get stored in database.

Now how to write into an CSV File
for that we are going to use "fputcsv"
fputcsv  formats a line as csv and write it to the specified file handle.

for example


<?php

$list = array (

    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');


foreach ($list as $fields) {

    fputcsv($fp, $fields);
}

fclose($fp);


?>


Following code will write into CSV File.

        


2 comments: