1

我有一个 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);           
}
4

1 回答 1

0

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

select something AS `new column name` FROM some_table
于 2012-12-11T11:55:27.777 回答