My HTML:
<h2>Download Example CSV - IN DEVELOPMENT (not working yet)</h2><br />
<form method="post" enctype="multipart/form-data">
<input type="submit" name="example-csv" value="Download Example" />
</form>
My PHP:
function array_to_csv_download($array, $filename = "example.csv", $delimiter=",") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
fclose($f);
}
if(isset($_POST['example-csv'])) {
$data = array (
array('column_1', 'column_2', 'column_3'),
array('test 1', 'test 2', 'test 3',)
);
array_to_csv_download($data);
}
What Happens:
When I click the Download Example submit button it gives me a file, example.csv. This file is pretty much all code for the current page I am on including all javascript, HTML, and anything else sent to the browser.
I can ctrl+F find the actual data I want in the mess.
My Question:
Why am I getting all the code for the page instead of just the simple CSV I am looking for?
Resources used to get to the point I am at:
How to create and download a csv file from php script?
Calling a particular PHP function on form submit
Final Notes:
I adapted the resources above to my needs, but can't seem to get what I am looking for. I hope this is detailed enough. Please ask for clarification if needed.
Thanks.
问题很简单,您必须在fclose之后添加出口或死掉 ,然后在文件数据之后将不再提供html代码。
I am not sure what you file structure is, but this is how it should be
Your HTML file:
<h2>Download Example CSV - IN DEVELOPMENT (not working yet)</h2><br />
<form method="post" action="ServeFile.php" enctype="multipart/form-data">
<input type="submit" name="example-csv" value="Download Example" />
</form>
PHP file ServerFile.php: It is the file PHP you put above, just make sure no spaces nothing before <?php and at the end.. (simply omit php closing tag ?> )
Since you are sending headers (header(..)) no output, even a space, should be sent before headers are sent, thus this file has to be a separate PHP file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.