phpyii

Displaying CSV file content in Yii Framework's CGridView


I am trying to display CSV file content in CGridView, I want to display CSV file header as CGridView "Column" and its content as DataProvider. Please provide any idea to achieve this?


Solution

  • You can use CArrayDataProvider. http://www.yiiframework.com/doc/api/1.1/CArrayDataProvider

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

    You can do something like this.

    $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
    ));
    

    If you want to create a generic data provider for CSV, you can create a new class.

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

    Then you can do something like this.

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