Home >Backend Development >PHP Tutorial >How to use header() to read and write csv files in php_PHP tutorial
Definition and usage
The header() function sends raw HTTP headers to the client.
It is important to realize that the header() function must be called before any actual output is sent (in PHP 4 and above, you can use output caching to solve this problem):
//The result is wrong
// Output already exists before calling header()
header('Location: http://www.zhutiai.com/');
?>Syntax
header(string,replace,http_response_code) parameter description
string required. Specifies the header string to be sent.
replace optional. Indicates whether this header replaces the previous header, or adds a second header.
Default is true (replacement). false (allow multiple headers of the same type).
http_response_code Optional. Forces the HTTP response code to the specified value. (Available in PHP 4 and above)
1. Define header() header output format
header("Content-type:application/vnd.ms-excel"); //Define the output file type
header(“content-Disposition:filename=downloaded.pdf”); //Define the output file name, that is, set a download type, and rename the file when downloading
header("Content-type:application/vnd.ms-excel");
header("content-Disposition:filename=downloaded.pdf ");echo "1t 2t 3n"; //where t is blank and n is carriage return (encoding specifications cannot be output directly)
echo"1t 2t 3n";
echo"1t 2t 3n";
?>
At this time, you can open the php file and you will be prompted to download it.
It can also be output in table format;
header("Content-type:application/vnd.ms-excel ");
header("content-Disposition:filename=downloaded.pdf");
?>
t00 t01 t02
t10 t11 t12
t20 t21 t22
CSV writing operation:
Please refer to the usage of fputcsv().
) must be called before any actual output is sent.$fp = fopen('f:/file.csv', 'w');
fputcsv($fp,array('aaa','bbb','cccc'));
fclose($fp);