导出Mysql到.txt -如何格式化文本


Exporting Mysql to .txt - how to format the text?

我正在导出一些mysql数据到文本文件。数据可以通过复选框从表中选择。

我想格式化文本,将在文本文件。我怎么做呢?

这是我的代码:

 <?php
if ($_POST['exporttxt']) {
for($i=0;$i<count($_POST['checkbox']);$i++){
   $export_id = $checkbox[$i];
$text = mysql_query("SELECT code FROM tickets WHERE id='$export_id'");
$text = mysql_fetch_assoc($text);
$text = $text["code"];
$filename = "export";
$filedate = date("Y-m-d");
$fileext = ".txt";
$fileall = $filename.$filedate.$fileext;
ob_end_clean();
    header("Content-Type: application/octet-stream");
header("Content-disposition: attachment;filename='"$fileall'"");
   header("Content-Type: application/force-download");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    header("Content-Length: ".strlen($output).";'n");

echo($text);

}
}
exit();
?>

导出的数据为16位以内的数字。每个数字后面都有一个换行符。另外,如果可能的话,我希望每个数字后面有一个空格,例如:

非格式化号码:1234567891234567号码格式:1234 5678 9123 4567

我该怎么做呢?

使用chunk_split

echo chunk_split($text, 4, " "); <-- you seems forgotten a line break

离题:-

  1. $output在哪里定义?
  2. 你没有ob_start()
  3. 反复使用$text用于各种数据类型(mysql结果资源,数组,字符串)

您需要将数字表示为字符串:

$num = preg_replace("/(?<='d)(?=('d{4})+(?!'d))/", " ", $num);

"1234567891234567"转化为"1234 5678 9123 4567"

新行用'n

表示

试试这个->

// divide in to chunks of 4 characters
$chunks = str_split($text['code'], 4);
//Convert array to string.  Each element separated by the given separator.
$result = implode(' ', $chunks);

工作示例:http://codepad.org/4Zf1ABKX