Codeigniter Library to Read CSV File
Posted on : 26-04-2011 | By : TheBizzTech | In : Codeigniter, Github, Model-View-Controller (MVC), PHP
Tags: Codeigniter, Github, MVC, PHP
7
I recently posted some code to Github that I created for use in Codeigniter. I built a library that can be used to read CSV files, extract the data you need, and return a PHP associative array.
Below I will post the code and a simple function that could be used in a Controller that would utilize the library.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* TheBizzTech
*
* An open source library built for Codeigniter to read CSV files into associated arrays
*
* @author Jason Michels
* @link http://thebizztech.com
*/
class Getcsv {
function get_csv_assoc_array($file_path, $questions)
{
$row = 0;
if (($handle = fopen($file_path, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, "", ",")) !== FALSE)
{
if($row == 0)
{
foreach ($questions as $key => $value)
{
foreach($data as $d_key => $d_value)
{
if($data[$d_key] == $value)
{
$q_location[$value] = $d_key;
}
}
}
}
else
{
foreach ($questions as $key => $value)
{
$new_row = $row -1;
$final_array[$new_row][$value] = $data[$q_location[$value]];
}
}
$row++;
}
fclose($handle);
}
return $final_array;
}
}
?>
Here is the example function:
function sample_read_csv()
{
$this->load->library('getcsv');
$data = array('name', 'email', 'id', 'transaction');
$csv_array = $this->getcsv->get_csv_assoc_array("path/to/file.csv", $data);
print_r($csv_array);
}
Right now this library only has one way of reading CSV files, but I hope to expand it over time.
To use the library you first have to load the library:
$this->load->library('getcsv');
After the library is loaded you have to create an array of column names that you know are in the CSV file and would like returned. Finally, call the library function and pass in the path to the file and the array you created, then print to see the results.
$data = array('name', 'email', 'id', 'transaction');
$csv_array = $this->getcsv->get_csv_assoc_array("path/to/file.csv", $data);
print_r($csv_array);
Let me know if there is any features you would like to see. You can find this code hosted on Github HERE.


thanks for the interesting information
There’s a terrific amount of knowledge in this aticrle!
That’s ralley thinking out of the box. Thanks!
Wham bam thank you, ma’am, my qutesions are answered!
Your cranium must be protecting some very valubale brains.
cool working fine for me thank you a lot
I just discovered this incredible weblog post and I should say to you thank you veryextremely much for giving this one to us.