Jump to content

How to format text written to a .txt file ?


thaidomizil

Recommended Posts

Hello everyone,

 

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?

You should never run queries in loops. How are you defining the $checkbox array? Is it from $_POST['checkbox'] or some other POST data?

 

You should be using the IN condition within your MySQL query with ALL the ids.

 

I don't think chunk_split() is really what you want to use. You would probably want each record to be on a line delimited using commas, tabs or spaces.

 

Anyway, here is an example (not tested).

if ($_POST['exporttxt'])
{
    $export_ids = implode(',', $_POST['export_ids']);
    $query = "SELECT code FROM tickets WHERE id IN ({$export_ids})";
    $result = mysql_query($query);

    $output = '';
    while($row = mysql_fetch_assoc($result))
    {
        $output .= implode(' ', str_split($row['code'], 4)) . "\n";
    }

    $filename = "export" . date("Y-m-d") . ".txt";
    ob_end_clean();
    header("Content-Type: application/octet-stream");
    header("Content-disposition: attachment;filename=\"$filename\"");
    header("Content-Type: application/force-download");

    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    header("Content-Length: ".strlen($output).";\n");
    echo($output);
}

exit();

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.