如何从csv读取/爆炸数据没有标题和分隔符,如|

时间:2013-12-26 15:59:28

标签: php codeigniter csv

我试图从Feed中读取数据,该文件可以保存为TXT或CSV。

让我们保存为CSV并尝试获取没有标题的数据,我的问题是我无法匹配每列的索引,我无法将这些行与分隔符和附件匹配。

该项目以codeigniter为基础。

库:

<?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,"\n");
        $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;
    }   
}
?>

控制器:

public function readCSV() {

        $this->load->library('csvreader');
        $result =   $this->csvreader->parse_file(base_url('test.csv'));

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

    }

查看:

<table class="table">
<thead>
    <tr>
        <td>Data1</td>
        <td>Data2</td>
        <td>Data3</td>
        <td>Data4</td>
        <td>Data5</td>
        <td>Data6</td>
        <td>Data7</td>
        <td>Data8</td>
        <td>Data9</td>
    </tr>
</thead>
<tbody>
<?php var_dump($csvData); ?>
<?php foreach($csvData as $field){?>
    <tr>
        <td><input type="text" name="data[]" value="<?php echo $field[0]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[1]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[2]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[3]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[4]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[5]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[6]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[7]; ?>"/></td>
        <td><input type="text" name="data[]" value="<?php echo $field[8]; ?>"/></td>
    </tr>
<?php }?>
</tbody>
</table>

CSV数据:

Category|||ID_590|Name|Description|url|imageurl.jpg|55.00|EUR||In stock|
Category|||ID_590|Name|Description|url|imageurl.jpg|55.00|EUR||In stock|
Category|||ID_590|Name|Description|url|imageurl.jpg|55.00|EUR||In stock|
Category|||ID_590|Name|Description|url|imageurl.jpg|55.00|EUR||In stock|

var_dump($csvData) result array(1006) { [1]=> array(0) { } [2]=> array(0) { } [3]=> ....

我做错了什么?

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

这是用第一行标题解析csv并用|

分隔的基本示例
<?php
if (($handle = fopen("csvparse.csv", "r")) !== FALSE) {
   $fields = fgetcsv($handle, null, "|");
    $retData = array();
    while (($data = fgetcsv($handle, null, "|")) !== FALSE) {
        $num = count($data);
        $arr = array();
        for ($c=0; $c < $num; $c++) {
            $arr[$fields[$c]] = $data[$c];
        }
        $retData[] = $arr;
    }
    fclose($handle);
    var_dump($retData);
}
?>

答案 1 :(得分:0)

这应该做的工作

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class CSVReader
{
    function parse_file($filePath, $separator = '|', $length = null, $enclosure = '"')
    {
        $fh = fopen($filePath, 'r');

        if($fh===false)throw new Exception("Couldn't read file");

        $keys = fgetcsv($fh, $length, $separator, $enclosure);
        $keyCount = count($keys);
        $content = array();
        while (($data = fgetcsv($fh, $length, $separator, $enclosure)) !== FALSE) {
            $count = count($data);
            if($count != $keyCount)continue;
            $contentArray = array();
            for ($c=0; $c < $count; $c++) {
                $contentArray[$keys[$c]] = $data[$c];
            }
            $content[] = $contentArray;
        }
        fclose($fh);
        return $content;
    }
}