我有一个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 .= "rn";
$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 .= "rn";
}
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);
}
也许您可以在SQL查询中使用AS
关键字?
select something AS `new column name` FROM some_table