how to read csv file in jquery using codeigniter framework

后端 未结 3 1229
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 10:16

suppose this is my csv file

fileempId,lastName,firstName,middleName,street1,street2,city,state,zip,gender,birthDate,ssn,empStatus,joinDate,workStation,locati         


        
3条回答
  •  醉酒成梦
    2021-01-07 11:07

    I use this library to convert array to some other data format or vice versa.

    CI - Rest Server

    There you can find library/class Format (Format.php) that you can use to convert CSV to array then save it into your database. This class also support other format:

    • xml – almost any programming language can read XML
    • json – useful for JavaScript and increasingly PHP apps.
    • csv – open with spreadsheet programs
    • html – a simple HTML table
    • php – Representation of PHP code that can be eval()’ed
    • serialize – Serialized data that can be unserialized in PHP

    EDIT:

    This library works on CSV with delimiter "\n" on each row and "," on each of column, you can use it like this:

    $this->load->library('format');
    
    $string_csv = "YOUR CSV";        
    $result = $this->format->factory($string_csv, 'csv')->to_array();
    
    var_dump($result);
    

    Just that simple. However as I said above if your have another delimiter then you have to adjust the library as your need. Here the main function to convert CSV to array:

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

    EDIT 2:

    My example will work on this standard CSV format:

    Heading1, Heading2, Heading3
    "1","John","London"
    "2","Brian","Texas"
    

提交回复
热议问题