DboSource::writeCsv PHP Method

writeCsv() public method

DBのデータをCSVファイルとして書きだす
public writeCsv ( array $options ) : boolean
$options array [ path / table / encoding ]
return boolean
    public function writeCsv($options)
    {
        $options = array_merge(array('path' => '', 'encoding' => '', 'table' => '', 'init' => false, 'plugin' => null), $options);
        extract($options);
        if (empty($path)) {
            return false;
        }
        if (empty($encoding)) {
            $encoding = $this->_dbEncToPhp($this->getEncoding());
        }
        if (empty($table)) {
            $table = basename($path, '.csv');
        }
        $schemas = $this->readSchema($table, array('plugin' => $plugin, 'cache' => false));
        if (!isset($schemas['tables'][$table])) {
            return false;
        }
        $_fields = array();
        foreach ($schemas['tables'][$table] as $key => $schema) {
            if ($key != 'indexes' && $key != 'tableParameters') {
                $_fields[] = $this->name($key);
            }
        }
        $fields = implode(',', $_fields);
        $appEncoding = Configure::read('App.encoding');
        $fullTableName = $this->config['prefix'] . $table;
        $sql = $this->renderStatement('select', array('table' => $this->name($fullTableName), 'fields' => $fields, 'conditions' => 'WHERE 1=1', 'alias' => '', 'joins' => '', 'group' => '', 'order' => '', 'limit' => ''));
        $datas = $this->query($sql);
        $fp = fopen($path, 'a');
        ftruncate($fp, 0);
        // ヘッダを書込
        if ($datas) {
            if (isset($datas[0][$fullTableName])) {
                $tablekey = $fullTableName;
            } else {
                $tablekey = 0;
            }
            $heads = array();
            foreach ($datas[0][$tablekey] as $key => $value) {
                $heads[] = '"' . $key . '"';
            }
        } else {
            $fields = array_keys($schemas['tables'][$table]);
            foreach ($fields as $field) {
                if ($field != 'indexes') {
                    $heads[] = '"' . $field . '"';
                }
            }
        }
        $head = implode(",", $heads) . "\n";
        if ($encoding != $this->config['encoding']) {
            $head = mb_convert_encoding($head, $encoding, $appEncoding);
        }
        fwrite($fp, $head);
        // データを書込
        foreach ($datas as $data) {
            $record = $data[$tablekey];
            if ($init) {
                $record['id'] = '';
                $record['modified'] = '';
                $record['created'] = '';
            }
            $record = $this->_convertRecordToCsv($record);
            $csvRecord = implode(',', $record) . "\n";
            if ($encoding != $appEncoding) {
                $csvRecord = mb_convert_encoding($csvRecord, $encoding, $appEncoding);
            }
            fwrite($fp, $csvRecord);
        }
        fclose($fp);
        return true;
    }
DboSource