如何通过PHP创建文本文件并在用户计算机中下载文本文件

I have tried several option but the text file saves in root server correctly but I want user to download the text file and save in his computer. I have got the download result by using

header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");

It downloads the whole script in user computer instead of only "text" result $textToWrite, which I want to download. Code I have tried are as follows:

$textToWrite = "$cdacode"."$cda_name"."$subofcode"."$subofname"."$name_payee"."$acno2"."$ifsc"."$micr_cd"."$act_type"."$pay_amt"."00"."DV NO"."$pmt_ref_no"."$paybydate"."$vendcode"."$vend_add"."$bill_num"."$billdate"."$narration"."$emailid"."$mob_num"."$addn_field";

$file= "$cmpno.txt" ;
$current .= "$textToWrite";

file_put_contents($file, $current);

header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");

Try this:

$textToWrite = "$cdacode"."$cda_name"."$subofcode"."$subofname"."$name_payee"."$acno2"."$ifsc"."$micr_cd"."$act_type"."$pay_amt"."00"."DV NO"."$pmt_ref_no"."$paybydate"."$vendcode"."$vend_add"."$bill_num"."$billdate"."$narration"."$emailid"."$mob_num"."$addn_field";

$file= "$cmpno.txt" ;
$current .= "$textToWrite";

file_put_contents($file, $current);

header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");
readfile($file);

As per my comments: as far as I can see, there are two issues with the code:

  • You have no opening PHP tag, and I wonder if you are just serving this script as text
  • You're pointlessly writing a file and then doing nothing with it

Try this code:

<?php

// @todo This rather needs tidying up
$textToWrite = "$cdacode"."$cda_name"."$subofcode"."$subofname".
    "$name_payee"."$acno2"."$ifsc"."$micr_cd"."$act_type".
    "$pay_amt"."00"."DV NO"."$pmt_ref_no"."$paybydate"."$vendcode".
    "$vend_add"."$bill_num"."$billdate"."$narration".
    "$emailid"."$mob_num"."$addn_field";
$file= "$cmpno.txt";

header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");
echo $textToWrite;

As per my comments the string is in a bit of a mess - try this first to see if we're on the right track, and if this broadly works, I'll show you how to tidy it up.