gpt4 book ai didi

php - 如何正确制作 Wordpress 插件返回可下载的 excel 文件

转载 作者:可可西里 更新时间:2023-11-01 01:01:01 24 4
gpt4 key购买 nike

我正在尝试为我的 wordpress 插件制作一些报告。此报告必须可以下载为 excel。基本上我所做的是创建一个按钮,当按下该按钮时,我将查询数据库并根据结果制作一个 excel。

现在我需要修改标题以将结果作为 excel 文件返回。我是这样做的:

header('Content-Disposition: attachment; filename='.$filename.'.xls');
header('Content-type: application/force-download');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
print "\xEF\xBB\xBF"; // UTF-8 BOM

问题是它返回以下错误:

Warning: Cannot modify header information - headers already sent by (output started at .....\wp-admin\menu-header.php:137) 

为此我可能需要 ob_start(),但不是说 ob_start() 必须放在第一个 header (来自 Wordpress 的核心文件)之前。如果可能,我不想修改核心文件。

或者 Wordpress 自己的钩子(Hook)“send_headers”?但我无法让它工作,它仍然会产生相同的错误。

那么我需要什么来解决这个问题呢?是否存在另一种从 wordpress 插件生成 excel 文件的方法?

感谢任何帮助!

最佳答案

你发送标题太晚了,因为 header() 已经在 menu-header.php 中发送了。从提供的代码中我看不到你在哪个点发送标题,但一个好的地方是 plugins_loaded Action ,因为在加载所有插件后以及发送任何输出之前调用该 Action Hook 。

下载链接可以是这样的:

<a href="<?php echo admin_url( '?download' ); ?>">download</a>

并且,plugins_loaded Action :

add_action( 'plugins_loaded', function() {
if ( isset( $_GET['download'] ) ) {
// here you can create .xls file

header('Content-Disposition: attachment; filename='.$filename.'.xls');
header('Content-type: application/force-download');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
die();
}
});

关于php - 如何正确制作 Wordpress 插件返回可下载的 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26506359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com