CodeIgniter版本3.1.11 -如何在CodeIgniter发布csv文件?



我是codeigniter的新手,我想使用这种输入法发布csv文件$this->input->post().我使用php的fopen()函数来读取csv文件,它需要文件名和参数中的路径。

这是一个简单的HTML文件。

<form method="post" class="form" action="<?php echo base_url('csv/store'); ?>" enctype="multipart/form-data">
    <label for="myfile">Select a file:</label>
    <input type="file" id="myfile" name="myfile" accept=".csv">
    <input type="text" id="name" name="name">
    <br />
    <input type="submit" class="submit" value="Submit"/>
</form>

这是我的控制器

public function store() {
        $x = $this->input->post('myfile');
        $y = $this->input->post('name');
        print_r($x);
        print_r($y);
        exit;      
}

如果我输出$x,它没有输出,但如果我输出$y,它有输出。

据我所知,您希望使用CI3读取服务器上上传的CSV文件。

在控制器方法store()中,执行以下操作-

  1. 您需要从服务器抓取上传的文件。CI3有一个库"upload",使用它。
  2. 使用fgetcsv()和fopen()读取数据

代码
public function store() {
        $fileName = $this->input->post('name');
        $uploadPath = "./upload/csv/";
        
        // Config the upload
        config['upload_path'] = $uploadPath; // some directory on the server with write permission
        
        // CHecking if present else create one
        if (!file_exists($config['upload_path'])) {
            if (!mkdir($concurrentDirectory = $config['upload_path'], 0777,
                    true) && !is_dir($concurrentDirectory)) {
                throw new RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
            }
        }
        $config['allowed_types'] = 'pdf';
        $config['max_size'] = '51200'; //50 MB
        $config['encrypt_name'] = false;
        $config['file_ext_tolower'] = true;
        
        // Set file name
        $config['file_name'] = $fileName;
        // Load the library with config
        $this->load->library('upload', $config);
        
        // Do the upload
        if ( ! $this->upload->do_upload('paper')){
            // On error
            die($this->upload->display_errors());
        }else{
            // Upload was success, File is present in "./upload/csv/" 
            $csvFile = $uploadPath . $uploadData['file_name'];
            
            // Read the CSV file
            $row = 1;
            // Open the file and adjust the code as per your need
            if (($handle = fopen($csvFile, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $num = count($data);
                    echo "<p> $num fields in line $row: <br /></p>n";
                    $row++;
                    for ($c=0; $c < $num; $c++) {
                        echo $data[$c] . "<br />n";
                    }
                }
                fclose($handle);
            }
        }
}

指向成员:以人类可读的形式命名变量、方法、函数、常量。

csv是一个文件…所以,使用print_r($_FILES);

相关内容

  • 没有找到相关文章

最新更新