在Yii Framework的CGridView中显示CSV文件内容

时间:2014-01-06 03:41:45

标签: yii

我想在CGridView中显示CSV文件内容,我想将CSV文件头显示为CGridView“Column”,其内容显示为DataProvider。请提供任何想法来实现这一目标?

1 个答案:

答案 0 :(得分:3)

您可以使用CArrayDataProvider。 http://www.yiiframework.com/doc/api/1.1/CArrayDataProvider

$dataProvider = new CArrayDataProvider(str_getcsv(file_get_contents('file.csv')));

你可以这样做。

$file = fopen('test.csv', 'r');
$data = array();
while (($line = fgetcsv($file)) !== FALSE) {
    //$line is an array of the csv elements
    $data[] = $line;
}
fclose($file);
$columns = array();
foreach ($data[0] as $key => $value) {
    $columns[] = array(
        'name' => $key,
        'header' => $value,
    );
}
$data = array_slice($data, 1);
$dataProvider = new CArrayDataProvider($data, array(
    'keyField' => 0,
));
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $dataProvider,
    'columns' => $columns
));

如果要为CSV创建通用数据提供程序,可以创建新类。

class CsvDataProvider extends CArrayDataProvider {

    private $_columns = array();

    public function __construct($file, $config = array()) {
        $handler = fopen($file, 'r');
        $data = array();
        while (($line = fgetcsv($handler)) !== FALSE) {
            $data[] = $line;
        }
        fclose($handler);
        $this->_columns = array();
        foreach ($data[0] as $key => $value) {
            $this->_columns[] = array(
                'name' => $key,
                'header' => $value,
            );
        }
        $data = array_slice($data, 1);
        parent::__construct($data, array_merge($config, array(
            'keyField' => 0,
        )));
    }

    public function getColumns() {
        return $this->_columns;
    }
}

然后你可以做这样的事情。

$dataProvider = new CsvDataProvider('file.csv');
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $dataProvider,
    'columns' => $dataProvider->getColumns(),
));