user990767
user990767

Reputation: 1019

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

I'm exporting some mysql data to a text file. The data can be selected by checkboxes from a table.

I want to format the text that will be in text file. How do I do that?

This is my code:

 <?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();

?>

The data that will be exported are numbers containing of 16 digits. After every number I want to have a line-break. Also if possible I would like to have a space after 4 digits for every number, example:

Number non-formatted: 1234567891234567 Number formatted: 1234 5678 9123 4567

How can I do that?

Upvotes: 0

Views: 339

Answers (3)

luastoned
luastoned

Reputation: 663

You need to represent the number as a string:

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

Turns "1234567891234567" into "1234 5678 9123 4567"

A new line would be represented by \n

Upvotes: 2

ajreal
ajreal

Reputation: 47311

Use chunk_split

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

Off-topic issue :-

  1. where is $output defined ?
  2. you don't have ob_start()
  3. repeatedly use $text for various data type( mysql result resource, array, string)

Upvotes: 3

Manse
Manse

Reputation: 38147

Try this ->

// 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);

Working example : http://codepad.org/4Zf1ABKX

Upvotes: 1

Related Questions