如何使用cakephp export txt文件

时间:2013-12-05 04:10:42

标签: cakephp

我正在使用cakephp框架。我想以两种格式导出客户端下载的数据库表。一个是'.csv',另一个是我通过'.svHelper'解析的'.txt'。CSV 。现在我想知道如何输出'.txt'。我的英语很差,但我想你会明白我的意思,谢谢!

2 个答案:

答案 0 :(得分:1)

基本上你设置了文件名的标题,如下所示:

        $this->response->type('Content-Type: text/csv');
    $this->response->download('myfilename.txt');

以下是我在appController中添加的一些功能,以便任何控制器都可以根据需要输出CSV文件:

    /**
 * Flattens the data that is returned from a find() operation, and puts it into CSV format
 * @param $data
 * @return string
 */
public function _arrayToCsvFile($data){
    $flattenedData = array();
    $exportKeyPair = array();
    foreach($data as $datumKey => $datumDetails){
        $flattenedDatum = Hash::flatten($datumDetails, '.');
        $flattenedData[] = $flattenedDatum;

        // Find all keys
        if($datumKey == 0){
            $exportKeys = array_keys($flattenedDatum);
            $exportKeyPair = array_combine($exportKeys, $exportKeys);
        }
        else {
            $datumKeys = array_keys($flattenedDatum);

            $datumKeyPair = array_combine($datumKeys, $datumKeys);

            // Add the datum keys to the exportKeyPair if it's not already there
            $exportKeyPair = array_merge($exportKeyPair, $datumKeyPair);
        }
    }

    $exportKeyMap = array();
    foreach($exportKeyPair as $exportKey => $exportValue){
        $exportKeyMap[$exportKey] = "";
    }


    $outputCSV = '';

    $outputCSV .= $this->_arrayToCsvLine($exportKeyPair);

    foreach($flattenedData as $flattenedDatumKey => $flattenedDatumDetails){

        // Add any extra keys
        $normalisedDatumDetails = array_merge($exportKeyMap, $flattenedDatumDetails);

        $outputCSV .= $this->_arrayToCsvLine($normalisedDatumDetails);
    }

    return $outputCSV;
}

    /**
 * arrayToCsvLine function - turns an array into a line of CSV data.
 *
 * @access public
 * @param mixed $inputLineArray the input array
 * @param string $separator (default: ")
 * @param string $quote (default: '"')
 * @return string
 */
function _arrayToCsvLine($inputLineArray, $separator = ",", $quote = '"') {
    $outputLine = "";

    $numOutput = 0;

    foreach($inputLineArray as $inputLineKey => $inputLineValue) {
        if($numOutput > 0) {
            $outputLine .= $separator;
        }

        $outputLine .= $quote . str_replace(array('"', "\n", "\r"),array('""', "", ""), $inputLineValue) . $quote;
        $numOutput++;
    }

    $outputLine .=  "\n";

    return $outputLine;

}

/**
 * Serves some CSV contents out to the client
 * @param $csvContents
 * @param array $options
 */
public function _serveCsv($csvContents, $options = array()){

    $defaults = array(
        'modelClass' => $this->modelClass,
        'fileName' => null
    );

    $settings = array_merge($defaults, $options);

    if(empty($settings['fileName'])){
        $settings['fileName'] = strtolower( Inflector::pluralize( $settings['modelClass'] ) ) . '_' . date('Y-m-d_H-i') . '.csv';
    }

    $this->autoRender = false;

    $this->response->type('Content-Type: text/csv');
    $this->response->download($settings['fileName']);
    $this->response->body($csvContents);
}

现在在任何控制器中都可以执行此操作(请注意,如果需要,您可以将文件名传递给_serveCsv):

/**
 * admin_export_csv method
 *
 * @return void
 */
public function admin_export_csv() {
    $this->Order->recursive = 0;

    $conditions = array();

    $orders = $this->Order->find('all', array('conditions' => $conditions));


    $csvContents = $this->_arrayToCsvFile($orders); // Function in AppController

    $this->_serveCsv($csvContents, array('filename' => 'export.txt')); // Function in AppController
}

答案 1 :(得分:0)

你可以使用
$ this-> RequestHandler-> respondAs('txt'); 输出正确的标头。
当DEBUG大于2时,请不要设置标题。
你仍然需要构建控制器动作并将视图设置为ususal。