我在尝试创建一个让某人下载的页面时遇到了问题。包含在前端变量中设置的数据的csv文件。
下面是我的代码,但唯一发生的事情是数据显示在页面中,但没有提示下载。csv文件。
有人知道问题出在哪里吗?
谢谢
Osu
<?php
/**
* CSV page template
*
*/
?>
<?php get_header(); ?>
<div id="sidebar-1">
<?php get_sidebar(); ?>
</div> <!-- End div#sidebar -->
<div id="primarycontent">
<?php get_template_part( \'/loop\', \'default\' ); ?>
<h2>Export</h2>
<form action="" method="post">
<input name="submit" type="submit" value="Export">
<input type="hidden" name="submit" />
</form>
<?php
// Check if form submitted before
if($_SERVER[\'REQUEST_METHOD\'] == "POST") {
$fileName = date("d-m-y") . \'-bv-directory.csv\';
$content = ""; // content added below
// Title of the CSV
$content = "Name,Address,Age,Phone \\n";
// Data in the CSV
$content .= "\\"John Doe\\",\\"New York, USA\\",15,65465464 \\n";
// Create csv and force download
header(\'Content-Type: application/csv\');
header("Content-length: " . filesize($NewFile));
header(\'Content-Disposition: attachment; filename="\' . $fileName . \'"\');
echo $content;
} ?>
</div> <!-- End div#primarycontent -->
<?php get_footer(); ?>
最合适的回答,由SO网友:TheDeadMedic 整理而成
将处理CSV输出的代码放在get_header()
那就给我打电话exit
:
<?php
/**
* CSV page template
*
*/
if($_SERVER[\'REQUEST_METHOD\'] == "POST") {
$fileName = date("d-m-y") . \'-bv-directory.csv\';
$content = ""; // content added below
// Title of the CSV
$content = "Name,Address,Age,Phone \\n";
// Data in the CSV
$content .= "\\"John Doe\\",\\"New York, USA\\",15,65465464 \\n";
// Create csv and force download
header(\'Content-Type: application/csv\');
header("Content-length: " . filesize($NewFile));
header(\'Content-Disposition: attachment; filename="\' . $fileName . \'"\');
echo $content;
exit;
}
?>
<?php get_header(); ?>
<div id="sidebar-1">
<?php get_sidebar(); ?>
</div> <!-- End div#sidebar -->
<div id="primarycontent">
<?php get_template_part( \'/loop\', \'default\' ); ?>
<h2>Export</h2>
<form action="" method="post">
<input name="submit" type="submit" value="Export">
<input type="hidden" name="submit" />
</form>
</div> <!-- End div#primarycontent -->
<?php get_footer(); ?>