从MySQL表创建一个tsv文件。添加更多虚构的标题

时间:2012-12-11 11:52:45

标签: php csv export-to-csv

我有一个MySQL表,我从中创建了tsv和csv文件。我想创建tsv文件,同时向文件添加虚构的标头。我已经使用MySQL列标题作为文件的标题,但我需要在MySQL表中添加额外的虚构标题。我当前的代码创建了该文件,但我不知道如何添加虚构的标题。

输出

name    age address
Daniel  24  Carlifornia
Jane    22  New York

我想输出

name    age address option1 option2
Daniel  24  Carlifornia anything    anything
Jane    22  New York    anything    anything

这是我的代码:

@chmod($export_tsv, 0777);
$fe = @fopen($export_tsv."/export.tsv", "w+");
if($fe){           
    $somecontent = "";
    //$somecontent = "header('Content-type: text/html; charset=utf-8')";
    $fields_count = 0;

    // fields headers
    $db->query($sql_view);
    if($row = $db->fetchAssoc()){
        foreach($row as $key => $val){
            if($fields_count++ > 0) $somecontent .= "\t";
            // mysql column headers here
            $somecontent .= $key;
        }
    }
    $somecontent .= "\r\n"; 

    $db->query($sql_view);
    while($row = $db->fetchAssoc()){
        $fields_count = 0;
        foreach($row as $key => $val){
            if($fields_count++ > 0) $somecontent .= "\t";
            //my own special code start
            $val = str_replace("\n","", $val);
            $val = str_replace("\r","", $val);
            $val = str_replace("\t","", $val);

            $val = stripslashes($val);                    
            $val = str_replace("chr(13)","", $val);
            //my own special code end

            $somecontent .= $val;              
        }
        $somecontent .= "\r\n"; 
    }
    utf8_encode($somecontent);
    $somecontent = mb_convert_encoding($somecontent, 'HTML-ENTITIES', "UTF-8");

    // write some content to the opened file.
   if (fwrite($fe, utf8_encode($somecontent)) == FALSE)
       echo 'file_writing_error'." (export.tsv)"; 
   fclose($fe);           
}

1 个答案:

答案 0 :(得分:0)

也许您可以在SQL查询中使用AS关键字?

select something AS `new column name` FROM some_table