我为客户端构建了一个插件,以便他们可以将数据下载为 CSV 文件。它已经设置为当用户单击菜单中的链接时,CSV 应该会自动下载。然而,它并不是那样工作的,它只是在 WordPress 后端将函数作为一个页面加载。
这是我的函数代码:
function download_payment_csv() {
include 'lib/connection.php';
$csv_output = '';
$values = $db->query('SELECT * FROM tbPayments ORDER BY date DESC');
$i=0;
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"report.csv\";" );
header("Content-Transfer-Encoding: binary");
echo $csv_output;
}
正如我所说,它只是返回一个空白屏幕。任何帮助,将不胜感激!
编辑
所以这是我现在正在使用的代码,从已经说过的内容中提取一些内容。
function download_payment_csv() {
include 'lib/connection.php';
$csv_output = '';
$values = load_payment_csv();
$fp = fopen("php://output", "w");
$file = 'test_export';
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=".$filename.".csv");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies
header("Content-Transfer-Encoding: UTF-8");
if(count($values) > 0) {
foreach($values as $result) {
fputcsv($fp, $result);
}
}
fclose($fp);
}
这会生成一个 CSV,但它有一个问题。问题是在查看页面时它不会将其下载为 CSV,它只是将 CSV 的内容输出到页面中。但是,将此功能添加到插件的顶部:
add_action('admin_init','download_payment_csv');
当单击菜单链接时,这会触发下载,这很好。但是它会为插件中的每个菜单项触发它,这是错误的。它应该只在点击下载链接时触发。
最佳答案
/**
* 查询顶部标题行
*/
$results = $wpdb->get_results("SHOW COLUMNS FROM $table" );
if(count($results) > 0){
foreach($results as $result){
$csv_output .= str_replace('_',' ',$result->Field).", "; // , or ;
}
}
$csv_output .= "\n";
/**
* 查询所有需要的数据
*/
$results = $wpdb->get_results("SELECT * FROM $table",ARRAY_A );
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
/**
* 准备要导出的文件名和 CSV 文件
*/
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
把这一切都放在一个函数中应该可以解决问题
关于php - 如何从 WordPress 插件中的函数下载 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32012440/