How to read a file
This post will explain how to read and write files using php. When reading a file from php, we can let the user select the file or we can give a specific file manually. Here is a explanation for reading and writing a csv file.if (!empty($_POST) && $_POST['file_upload']) { $target_file = '/tmp/' . basename($_FILES["file_name"]["name"]); $fileType = pathinfo($target_file,PATHINFO_EXTENSION); if($fileType =='csv'){ // read the csv file. Discussed below }else{ $this->session->set_flashdata('error_message', "Please upload valid file type"); }
Here we have check
if the is a post(that means submit button has been pressed). Then we
have uploaded the file to a folder called tmp. Then we check the file
format(whether it is csv or not).
Then we set some
config$config['upload_path'] = '/tmp'; $config['allowed_types'] = '*'; $config['max_size'] = '3024000'; $config['max_filename'] = '255'; $config['encrypt_name'] = TRUE;
When we read the
csv, it gives a row as one array, columns are separated by a comma.
We open the csv file
by using fopen
$file = '/tmp/' . $file['file_name'];$file_handle = fopen($file, 'r');
We read file row by
row and store each row as an array in a array. The columns are
separated by using a comma. This process continuous until end of the
file and then close the file.
$pieces = array(); while (!feof($file_handle)) { $line_of_text = fgetcsv($file_handle, 4096, $separator); if (is_array($line_of_text)) { $pieces[] = explode(",", implode($line_of_text)); } } fclose($file_handle);
Use of $pieces[] = explode(",", implode($line_of_text)); is, when we get a
row to an array, it needed to be breakdown by the comma. By using it
we can individually call columns. $pieces[] contains the csv
line by line.
How to write a file
First we give a name
for the file and a path
$file_name = 'details.csv'; $file = FCPATH.'assets/csv/'.$file_name;
FCPATH is use to identify the full path (This file is stored in assets
folder, csv folder).
Then we open the csv
file.
$handle = fopen($file, 'a');
Here I have used “a”
for append. It will only append the csv. That means it will write to
the csv without clearing the whole csv. If we use “w” to write,
it will delete all records in the csv and start write from the
beging.
First of all, we can
put a header title for the csv file.
$csvRow = array('id', 'name', 'description', ...);$trimmed_array = array_map('trim', $csvRow);fputcsv($handle, $trimmed_array);
By using
fputcsv($handle, $trimmed_array); we can put a line to csv. Then by using a loop, we can put all data
to csv as above and finally we close the file.
Hope you find this useful.
Like us on facebook
Hope you find this useful.
Comments
Post a Comment