Php 如何在Codeigniter中仅设置或上载CSV类型
我正在尝试将CSV导入MYSQL数据库。我学习了一个教程 现在我得到一个错误 不允许您尝试上载的文件类型 以下是我的控制器代码:Php 如何在Codeigniter中仅设置或上载CSV类型,php,mysql,codeigniter,csv,Php,Mysql,Codeigniter,Csv,我正在尝试将CSV导入MYSQL数据库。我学习了一个教程 现在我得到一个错误 不允许您尝试上载的文件类型 以下是我的控制器代码: function importcsv() { $data['addressbook'] = $this->csv_model->get_addressbook(); $data['error'] = ''; //initialize image upload error array to empty $config['upl
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'text/x-comma-separated-values'|'text/comma-separated-values'|'application/octet-stream'| 'application/vnd.ms-excel'|'application/x-csv'|'text/x-csv'|'text/csv'|'application/csv'|'application/excel'|'application/vnd.msexcel'|'text/plain';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
public function chk_attachment() // callback validation for check the attachment extension
{
$file_type = array('.csv');
if(!empty($_FILES['uploaded_file']['name']))
{
$ext = strtolower(strrchr($_FILES['uploaded_file']['name'],"."));
if(in_array($ext,$ext_array))
{
return true;
}
else
{
$this->form_validation->set_message('chk_attachment','Attachment allowed only csv');
return false;
}
}
{
$this->form_validation->set_message('chk_attachment','image field is required');
return false;
}
}
函数importsv(){
$data['addressbook']=$this->csv_model->get_addressbook();
$data['error']='';//将图像上载错误数组初始化为空
$config['upload_path']='./uploads/';
$config['allowed_types']='text/x-comma-separated-values'|'text/comma-separated-values'|'application/octet stream'|'application/vnd.ms excel'|'application/x-csv'|'text/x-csv'|'text/csv'|'application/excel'|application/vnd.msexcel'|'text/plain';
$config['max_size']='1000';
$this->load->library('upload',$config);
//如果上载失败,则显示错误
如果(!$this->upload->do_upload()){
$data['error']=$this->upload->display_errors();
$this->load->view('csvindex',$data);
}否则{
$file_data=$this->upload->data();
$file_path='./上载/'.$file_数据['file_name'];
if($this->csvimport->get_数组($file_路径)){
$csv_数组=$this->csvimport->get_数组($file_path);
foreach($csv\u数组作为$row){
$insert_data=数组(
“firstname”=>$row[“firstname”],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv\u model->insert\u csv($insert\u data);
}
$this->session->set_flashdata('success','Csv Data Imported successfully');
重定向(base_url().“csv”);
//回显“;打印(插入数据);
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter CSV Import Class
*
* This library will help import a CSV file into
* an associative array.
*
* This library treats the first row of a CSV file
* as a column header row.
*
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author Brad Stinson
*/
class Csvimport {
private $filepath = "";
private $handle = "";
private $column_headers = "";
/**
* Function that parses a CSV file and returns results
* as an array.
*
* @access public
* @param filepath string Location of the CSV file
* @param column_headers array Alternate values that will be used for array keys instead of first line of CSV
* @param detect_line_endings boolean When true sets the php INI settings to allow script to detect line endings. Needed for CSV files created on Macs.
* @return array
*/
public function get_array($filepath='', $column_headers='', $detect_line_endings=FALSE)
{
// If true, auto detect row endings
if($detect_line_endings){
ini_set("auto_detect_line_endings", TRUE);
}
// If file exists, set filepath
if(file_exists($filepath))
{
$this->_set_filepath($filepath);
}
else
{
return FALSE;
}
// If column headers provided, set them
$this->_set_column_headers($column_headers);
// Open the CSV for reading
$this->_get_handle();
$row = 0;
while (($data = fgetcsv($this->handle, 0, ",")) !== FALSE)
{
// If first row, parse for column_headers
if($row == 0)
{
// If column_headers already provided, use them
if($this->column_headers)
{
foreach ($this->column_headers as $key => $value)
{
$column_headers[$key] = trim($value);
}
}
else // Parse first row for column_headers to use
{
foreach ($data as $key => $value)
{
$column_headers[$key] = trim($value);
}
}
}
else
{
$new_row = $row - 1; // needed so that the returned array starts at 0 instead of 1
foreach($column_headers as $key => $value) // assumes there are as many columns as their are title columns
{
$result[$new_row][$value] = trim($data[$key]);
}
}
$row++;
}
$this->_close_csv();
return $result;
}
/**
* Sets the filepath of a given CSV file
*
* @access private
* @param filepath string Location of the CSV file
* @return void
*/
private function _set_filepath($filepath)
{
$this->filepath = $filepath;
}
/**
* Sets the alternate column headers that will be used when creating the array
*
* @access private
* @param column_headers array Alternate column_headers that will be used instead of first line of CSV
* @return void
*/
private function _set_column_headers($column_headers='')
{
if(is_array($column_headers) && !empty($column_headers))
{
$this->column_headers = $column_headers;
}
}
/**
* Opens the CSV file for parsing
*
* @access private
* @return void
*/
private function _get_handle()
{
$this->handle = fopen($this->filepath, "r");
}
/**
* Closes the CSV file when complete
*
* @access private
* @return array
*/
private function _close_csv()
{
fclose($this->handle);
}
}
}否则
$data['error']=“发生错误”;
$this->load->view('csvindex',$data);
}
}
公共函数chk_attachment()//检查附件扩展的回调验证
{
$file_type=数组('.csv');
如果(!空($_文件['Upload_文件]['name']))
{
$ext=strtolower(strrchr($_文件['uploaded_文件]]['name'],”);
if(in_数组($ext,$ext_数组))
{
返回true;
}
其他的
{
$this->form_validation->set_message('chk_attachment','attachment allowed only csv');
返回false;
}
}
{
$this->form_validation->set_message('chk_attachment','image field is required');
返回false;
}
}
这个回调函数是stackoverflow上的一个用户建议的,他解决了同一个问题,但不知何故对我不起作用。我有一个用户表,我只想插入用户使用上传的CSV,但不知何故它不允许我上传CSV
这是图书馆
'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel')
添加$config['allowed_types']='csv';到您的$config数组
如需更多帮助,请查看
还要浏览路径上的文件application\config\mimes.php,以更清楚地了解csv数组对文件上载类型的支持
如果确实需要,可以更新此阵列
新文件上传用户指南位置@Saty我尝试过,但同样的错误我认为除了codeHi的那部分之外,还有其他错误。我保留了这个,但不好。它总是显示错误。可能我使用Print_r($_文件)检查codeCheck文件细节的其他部分有问题;检查文件类型是否属于csv数组。我应该在何处执行此操作??首先在初始化的$config['allowed_types']中将“|”替换为“|”,然后使用print_r after语句$this->load->library('upload',$config));