php CodeIgniter 的 CSV 导入库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15446796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:15:29  来源:igfitidea点击:

CSV Import Library for CodeIgniter

phpcsvcodeigniter-2helperxls

提问by Ivan Slaughter

Need to implement csv or xls import into Application created using CodeIgniter. Is there any library for this? Any suggestion appreciated.

需要将 csv 或 xls 导入使用 CodeIgniter 创建的应用程序。有没有这方面的图书馆?任何建议表示赞赏。

回答by Muhammad Raheel

Here is an easy way to do this. I don't know what people do but i use this

这是一个简单的方法来做到这一点。我不知道人们在做什么,但我使用这个

This is my csv reader library

这是我的 csv 阅读器库

<?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;
    }   
}
?> 

And controller method

和控制器方法

function readExcel()
{
        $this->load->library('csvreader');
        $result =   $this->csvreader->parse_file('Test.csv');

        $data['csvData'] =  $result;
        $this->load->view('view_csv', $data);  
}

And this is view

这是视图

<table cellpadding="0" cellspacing="0" width="100%">
    <tr>
            <td width = "10%">ID</td>
            <td width = "20%">NAME</td>
            <td width = "20%">SHORT DESCRIPTION</td>
            <td width = "30%">LONG DESCRIPTION</td>
            <td width = "10%">STATUS</td>
            <td width = "10%">PARENTID</td>
    </tr>

            <?php foreach($csvData as $field){?>
                <tr>
                    <td><?php echo $field['id']?></td>
                    <td><?php echo $field['name']?></td>
                    <td><?php echo $field['shortdesc']?></td>
                    <td><?php echo $field['longdesc']?></td>
                    <td><?php echo $field['status']?></td>
                    <td><?php echo $field['parentid']?></td>
                </tr>
            <?php }?>
</table>

Reference Here

参考这里

回答by ajmedway

This is an improved version of raheel shan's accepted answer - I edited his answer but my edit was rejected, however it is an important change...

这是 raheel shan 接受的答案的改进版本 - 我编辑了他的答案,但我的编辑被拒绝了,但这是一个重要的变化......

When parsing each data row, it is not wise to use explode()on the comma as this does not handle quote-encased strings that contain commas. Explode breaks those strings into substrings and gives extra array elements in $values, so this check fails:

解析每个数据行时,explode()在逗号上使用是不明智的,因为这不处理包含逗号的引号包裹的字符串。Explode 将这些字符串分解为子字符串并在 中提供额外的数组元素$values,因此此检查失败:

if (count($keys) == count($values)) {

Instead, PHP has a purpose-built method to handle this; str_getcsv(). I have updated the original answer code accordingly.

相反,PHP 有一个专门构建的方法来处理这个问题;str_getcsv()。我已经相应地更新了原始答案代码。

The CSV Reader library:

CSV 阅读器库:

<?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 = str_getcsv($this->fields[0]);

        $i = 1;
        while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
            if ($row != null) { // skip empty lines
                $values = str_getcsv($row[0]);
                if (count($keys) == count($values)) {
                    $arr = array();
                    for ($j = 0; $j < count($keys); $j++) {
                        if ($keys[$j] != "") {
                            $arr[$keys[$j]] = $values[$j];
                        }
                    }

                    $content[$i] = $arr;
                    $i++;
                }
            }
        }
        fclose($file);
        return $content;
    }

}
?>

Controller method:

控制器方法:

function readExcel() {
    $this->load->library('csvreader');
    $result = $this->csvreader->parse_file('Test.csv');
    $data['csvData'] = $result;
    $this->load->view('view_csv', $data);
}

And this is the view:

这是观点:

<table cellpadding="0" cellspacing="0" width="100%">
    <tr>
        <td width="10%">ID</td>
        <td width="20%">NAME</td>
        <td width="20%">SHORT DESCRIPTION</td>
        <td width="30%">LONG DESCRIPTION</td>
        <td width="10%">STATUS</td>
        <td width="10%">PARENTID</td>
    </tr>
    <?php foreach ($csvData as $field) { ?>
        <tr>
            <td><?php echo $field['id'] ?></td>
            <td><?php echo $field['name'] ?></td>
            <td><?php echo $field['shortdesc'] ?></td>
            <td><?php echo $field['longdesc'] ?></td>
            <td><?php echo $field['status'] ?></td>
            <td><?php echo $field['parentid'] ?></td>
        </tr>
    <?php } ?>
</table>

回答by Ayaskant Mishra

Well don't mind me, I just modified ajmedway's library to include delimiters just in case you wanted to get data from lets say TSV or pipes delimited files. If you want plain old CSV his is just fine.

好吧,别介意我,我只是修改了 ajmedway 的库以包含分隔符,以防万一您想从 TSV 或管道分隔文件中获取数据。如果你想要普通的旧 CSV,他就可以了。

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, $delimiter = FALSE ) {

    $file = fopen($p_Filepath, 'r');
    $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
    if ($delimiter==FALSE)
    {
    $keys = str_getcsv($this->fields[0]);

    $i = 1;
    while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
        if ($row != null) { // skip empty lines
            $values = str_getcsv($row[0]);
            if (count($keys) == count($values)) {
                $arr = array();
                for ($j = 0; $j < count($keys); $j++) {
                    if ($keys[$j] != "") {
                        $arr[$keys[$j]] = $values[$j];
                    }
                }

                $content[$i] = $arr;
                $i++;
            }
        }
    }
    }
    else{
        $keys = str_getcsv($this->fields[0],$delimiter);

        $i = 1;
        while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
            if ($row != null) { // skip empty lines
                $values = str_getcsv($row[0],$delimiter);
                if (count($keys) == count($values)) {
                    $arr = array();
                    for ($j = 0; $j < count($keys); $j++) {
                        if ($keys[$j] != "") {
                            $arr[$keys[$j]] = $values[$j];
                        }
                    }

                    $content[$i] = $arr;
                    $i++;
                }
            }
        }
    }

    fclose($file);
    return $content;
}}?>

回答by mahek kakadiya

This is an improved version for empty lines and extra spaces and tabs...

这是空行和额外空格和制表符的改进版本......

class CSVReader {

类 CSVReader {

function csv_to_array($Filepath)
{
    //Get csv file content
    $csvData = file_get_contents($Filepath);

    //Remove empty lines
    $csvData = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $csvData);

    //String convert in array formate and remove double quote(")
    $array = array();
    $array = $this->escape_string(preg_split('/\r\n|\r|\n/', $csvData));
    $new_content_in_array = array();
    if($array)
    {
        //Get array key
        $array_keys = array();
        $array_keys = array_filter(array_map('trim', explode(';',$array[0])));

        //Get array value
        $array_values = array();
        for ($i=1;$i<count($array);$i++)
        {
            if($array[$i])
            {
                $array_values[] = array_filter(array_map('trim', explode(';',$array[$i])));
            }
        }

        //Convert in associative array
        if($array_keys && $array_values)
        {
            $assoc_array = array();
            foreach ($array_values as $ky => $val)
            {           
                for($j=0;$j<count($array_keys);$j++){
                    if($array_keys[$j] != "" && $val[$j] != "" && (count($array_keys) == count($val)))
                    {
                        $assoc_array[$array_keys[$j]] = $val[$j];
                    }
                }
                $new_content_in_array[] = $assoc_array;
            }
        }
    }
    return $new_content_in_array;
}

function escape_string($data){
    $result =   array();
    foreach($data as $row){
        $result[]   = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", str_replace('"', '',$row));
    }
    return $result;
}   

} ?>

} ?>

回答by mahek kakadiya

Call in controller:

调用控制器:

$this->load->library('csvreader');
$import_csv_data = $this->csvreader->csv_to_array($path);
print_r($import_csv_data );
exit;