假设这是我的csv文件
fileempId,lastName,firstName,middleName,street1,street2,city,state,zip,gender,birthDate,ssn,empStatus,joinDate,workStation,location,custom1,workState,salary,payFrequency,FITWStatus,FITWExemptions,DD1Routing,DD1Account,DD1Amount,DD1AmountCode,DD1Checking,DD2Routing,DD2Account,DD2Amount,DD2AmountCode,DD2Checking
1,Dela Cruz,Juano,Santos,,,,,,1,,,Part Time Internship,, asd Division, Makati,one, asd,150,Bi Weekly,Not Applicable,100,,,,,,1234,9876,100,SAVINGS,BLANK
3,Palogan,Ralph,,,,,,,1,11-Mar-11,,Full Time Contract,2-Mar-11, sdf Department, pasay,, ,,,Not Applicable,,,,,,,,,,, 5,San,Goku,,,,hidden leaf,,,1,11-Mar-11,,,,,,,,,,Not Applicable,0,,,,,,,,,,
这是我的表格
<label>Choose File:</label><font color="#FF0000">*</font>
<input type="file" name="file" id="file" />
<input type="button" id="importButton" value="Import" name="importButton" />
如何读取csv中的数据并将其存储到mysql数据库(codeigniter)?有关如何操作的任何示例代码,。
请看下面我的代码有什么问题,..,
我的视图页面包含jquery和表单,,。
<td><label>Choose File:</label><font color="#FF0000">*</font></td>
<td><input type="file" name="file" id="file" /></td>
<td><label>Import Type </label><font color="#FF0000">*</font></td>
<td><select name="importname" id="importname" style="width:130px;">
<option value="" selected>--Select--</option>
<?php
foreach($fields as $data){
print '<option value="'.$data->import_id.'">'.$data->name.'</option>';
}
?>
</select></td>
<script type="text/javascript">
$(function() {
$("#importData").click(function(e) {
var file = $('#file').val();
var type = $('#importname').val();
$.post("<?php print base_url().'index.php/MyController/readExcel'?>",{file: file, type: type},
function(data)
{
if(data!='success')
{
error_message(data);
}
else{
alert("Upload Succcessfull!");
}
});
});
});
</script>
我的控制器
function readExcel(){
$file=$this->input->post('file');
$type=$this->input->post('type');
$this->load->library('csvreader');
$result = $this->csvreader->parse_file($file);
$data['csvData'] = $result;
$this->load->view('MyViews/showImportFile', $data);
}
我的图书馆
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class csvreader {
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 = 4096; /** 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, $this->max_row_size, $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;
}
}
我收到错误
遇到PHP错误
严重性:警告
消息:fopen(export 1.csv):无法打开流:没有这样的文件或目录
文件名:libraries / csvreader.php
有人可以帮我吗!!!
答案 0 :(得分:0)
我使用此库将数组转换为其他数据格式,反之亦然。
在那里你可以找到库/类Format(Format.php),你可以用它将CSV转换为数组,然后将其保存到数据库中。该类还支持其他格式:
修改强>
此库适用于每行上带有分隔符“\ n”的CSV,每列上的“,”,您可以像这样使用它:
$this->load->library('format');
$string_csv = "YOUR CSV";
$result = $this->format->factory($string_csv, 'csv')->to_array();
var_dump($result);
就这么简单。但是,如上所述,如果您有另一个分隔符,则必须根据需要调整库。这里是将CSV转换为数组的主要功能:
function _from_csv($string)
{
$data = array();
// Splits
$rows = explode("\n", trim($string));
$headings = explode(',', array_shift($rows));
foreach ($rows as $row)
{
// The substr removes " from start and end
$data_fields = explode('","', trim(substr($row, 1, -1)));
if (count($data_fields) == count($headings))
{
$data[] = array_combine($headings, $data_fields);
}
}
return $data;
}
编辑2:
我的示例将使用此标准CSV格式:
Heading1, Heading2, Heading3
"1","John","London"
"2","Brian","Texas"
答案 1 :(得分:0)
根据您的评论,实际上您要先将CSV文件上传到服务器,然后检查CSV字段/标题是否与您的某个数据库表字段匹配以插入行,这里是我制作的示例代码:
CSV阅读器(基于此 library 进行一些调整):
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* CSVReader Class
*
* $Id: csvreader.php 147 2007-07-09 23:12:45Z Pierre-Jean $
*
* Allows to retrieve a CSV file content as a two dimensional array.
* The first text line shall contains the column names.
*
* @author Pierre-Jean Turpeau
* @link http://www.codeigniter.com/wiki/CSVReader
*/
class CSVReader {
var $fields; /** columns names retrieved after parsing */
var $separator = ','; /** separator used to explode each line */
/**
* Parse a text containing CSV formatted data.
*
* @access public
* @param string
* @return array
*/
function parse_text($p_Text) {
$lines = explode("\n", $p_Text);
return $this->parse_lines($lines);
}
/**
* Parse a file containing CSV formatted data.
*
* @access public
* @param string
* @return array
*/
function parse_file($p_Filepath) {
$lines = file($p_Filepath);
return $this->parse_lines($lines);
}
/**
* Parse an array of text lines containing CSV formatted data.
*
* @access public
* @param array
* @return array
*/
function parse_lines($p_CSVLines) {
$content = FALSE;
foreach( $p_CSVLines as $line_num => $line ) {
if( $line != '' ) { // skip empty lines
$line = trim($line);
$elements = explode($this->separator, $line);
if( !is_array($content) ) { // the first line contains fields names
$this->fields = $elements;
$content = array();
} else {
$item = array();
foreach( $this->fields as $id => $field ) {
if( isset($elements[$id]) ) {
$item[$field] = $elements[$id];
}
}
$content[] = $item;
}
}
}
return $content;
}
/**
* Get fields
*/
public function get_fields(){
return $this->fields;
}
}
在CI上执行上传处理程序:
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('csvfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('csv_upload', $error);
}
else
{
$upload_data = $this->upload->data();
// start to read the CSV file
$this->load->library('csvreader');
$file_path = $upload_data['full_path'];
$csv_data = $this->csvreader->parse_file($file_path);
$csv_fields = $this->csvreader->get_fields();
// list your database table
$tables = $this->db->list_tables();
foreach($tables as $table)
{
$fields = $this->db->list_fields($table);
if($fields == $csv_fields) // match to one of database table
{
// insert the record
foreach($csv_data as $row){
$this->db->insert($table, $row);
}
}
}
$data = array(
'upload_data' => $upload_data,
'csv_data' => $csv_data,
);
$this->load->view('upload_success', $data);
}
}
下载完整示例 HERE 。您可以在文件夹uploads
中找到CSV文件的样本。
答案 2 :(得分:0)
我已经尝试过您的CSVReader函数。根据我的需要,它给我完美的结果。我也喜欢您的想法,请检查CSV字段/标题是否与您的数据库表字段之一匹配以插入行。它给出结果数组如下。
Array
(
[0] => Array
(
[Years] => 1888
[Make1] => Acura
[Make2] => Honda
[Make] => Honda
[] => Honda
[Makes] => Toyota
)
我也在此位置尝试了CSVReader库。 https://github.com/bcit-ci/CodeIgniter/wiki/CSVReader 但是,它给出的结果数组的值由comma(,)内推,如下所示。
Array
(
[0] => Array
(
[Years,Make1,Make2,Make,,Makes,Make] => 1888,Acura,Honda,Toyota,Honda,Toyota,Honda
)
)
现在SubRed,在您的CSVReader函数中,我对CSV文件的第一行名称进行了更改,并在末尾添加了空格。但是在那之后,在CI控制器中,当我检查带有array_key_exists('column_name',$csvdata)
的CSV文件中的field / headers / column_name时,由于末尾column_name
字段中的空格,它返回false / none。所以我已经更新了您的代码。
请参考下面的更新代码,如有任何建议,请给我。
编辑:- 更改CSVReader文件中parse_lines函数中的foreach循环=>
foreach( $this->fields as $id => $field ) {
//echo $id;
//echo $field;
//In CSV File, trim(remove both end whitespaces) the first line which contains fields names
$field = trim($field);
if( isset($elements[$id]) )
{
$item[trim($field)] = trim($elements[$id]);//In CSV File, trim all the file data
}
}