header函数文件名在PHP中不起作用。我尝试导出CSV文件,但它始终仅下载页面名称,例如export.php 我尝试了很多代码并强制下载。但是我不能。请任何人帮助我
enter code here
if(isset($_POST["export"]))
{ include 'database/config.php';
include "database/database.php";
$db = new database();
$fn = "csv_".uniqid().".csv";
$file = fopen($fn, "w");
$query = "SELECT * from wp_terms";
$read = $db -> select($query);
fputcsv($file, array('ID', 'Name', 'slug', 'term group'));
if($read) {
while ($row = $read->fetch_assoc()) {
fputcsv($file, $row);
}
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$fn);
fclose($file);
}
答案 0 :(得分:0)
这将完全适合我,因此请尝试以下代码。
add_action("admin_init", "download_csv");
function download_csv() {
if (isset($_POST['download_csv'])) {
global $wpdb;
$sql = "SELECT `sub_email` FROM `wp_terms`";
$rows = $wpdb->get_results($sql, 'ARRAY_A');
if ($rows) {
$csv_fields = array();
$csv_fields[] = "first_column";
$csv_fields[] = 'second_column';
$current_date = date("Y-m-d");
$output_filename = 'subscriber_list'.$current_date.'.csv';
$output_handle = @fopen('php://output', 'w');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=' .
$output_filename);
header('Expires: 0');
header('Pragma: public');
$first = true;
// Parse results to csv format
foreach ($rows as $row) {
// Add table headers
if ($first) {
$titles = array();
foreach ($row as $key => $val) {
$titles[] = $key;
}
fputcsv($output_handle, $titles);
$first = false;
}
$leadArray = (array) $row; // Cast the Object to an array
// Add row to file
fputcsv($output_handle, $leadArray);
}
//echo '<a href="'.$output_handle.'">test</a>';
// Close output file stream
fclose($output_handle);
die();
}
}
}