PHP 重定向而不是建议下载

PHP redirect instead of proposing download

我在点击我正在创建的 wordpress 网站上的按钮时提出要保存的文件 (csv) 时遇到问题。我已将我的代码简化到最低限度,但它仍然无法正常工作。

我的模板页面代码:

<?php
/*
Template Name: My Awesome Custom Page
*/

get_header(); ?>
<html>
<form style= "text-align:center;" name="getcsv" action="test.php"      method="post">
 <select id="ddl">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> <br/>
<input  name= "export_excel" type="submit" value="Extraire"/>
</form>
</html>
<?php get_footer();

并且 test.php 文件有:

<?php

if(isset($_POST["export_excel"]))
{
header( 'Content-type: application/xls' );
header( 'Content-Disposition: attachment; filename="test.xls"');
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Pragma: public' ); 
$headers = array('Type of Activity', "Number of Activities", "Hours of         Instruction");
$row_1 = array($_POST['ddl'], $_POST['ddl'], $_POST['ddl']);
$output = implode(',',$headers);
$output.= "\n";
$output.= implode(',',$row_1);
$output.= "\n"; 
}
?>

当我点击该按钮时,它会将我从 http://localhost/test/pagedetest to http://localhost/test/pagedetest/test.php 重定向,我当然会收到 404,因为该页面从未创建过。

这只是一个测试用例,所以我可以在它的基础上做一些更复杂的事情,但即使这样也行不通。

我尝试使用 fputcsv 函数,而不是只是对 php://output 的简单回显,并使用 ajax 调用而不是表单,但这没有给我任何结果(没有错误或任何东西)

如果有人知道为什么会发生这种情况,请提前致谢!

抱歉,如果这是一个愚蠢的问题,但我的 google-fu 没有发现任何东西,而且我已经很久没有玩 wordpress 或 PHP...

干杯!

action="test.php" 会将表单提交到当前目录中名为 test.php 的文件。我猜你的 test.php 在 http://localhost/test/test.php or http://localhost/test.php。使用绝对路径(/test.php/test/test.php)作为您的操作,看看是否有帮助。