I’m working on a codeIgniter3 project where I need to upload CSV file into the database and I used custom made library for perform this task but it is not working and showing empty array!
here are the library that I used “Csvimport.php“:
<?php defined('BASEPATH') or exit('No direct script access allowed');
class Csvimport {
var $fields;/** columns names retrieved after parsing */
var $separator = ';';/** separator used to explode each line */
var $enclosure = '"';/** enclosure used to decorate each field */
var $max_row_size = 120400;/** maximum row size to be used for decoding */
function parse_file($p_Filepath) {
$file = fopen($p_Filepath, 'r');
$this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
$keys_values = explode(',', $this->fields[0]);
$content = array();
$keys = $this->escape_string($keys_values);
$i = 1;
while (($row = fgetcsv($file, 0, $this->separator, $this->enclosure)) != false) {
if ($row != null) { // skip empty lines
$values = explode(',', $row[0]);
if (count($keys) == count($values)) {
$arr = array();
$new_values = array();
$new_values = $this->escape_string($values);
for ($j = 0; $j < count($keys); $j++) {
if ($keys[$j] != "") {
$arr[$keys[$j]] = $new_values[$j];
}
}
$content[$i] = $arr;
$i++;
}
}
}
fclose($file);
return $content;
}
function escape_string($data) {
$result = array();
foreach ($data as $row) {
$result[] = str_replace('"', '', $row);
}
return $result;
}
}
?>
Here is the “Controller” code that I used to upload the CSV file:
$this->load->library('csvimport');
$file_path = base_url()."upload/test.csv";
$csv_data = $this->csvimport->parse_file($file_path);
echo '<pre>';
print_r($csv_data);
echo '</pre>';
When I executed code it show empty array() as result!
Please help me i’m stuck with this!! 🙁
In CSV file I’ve following fields:
grade
name
address
city
phone
email
type
created