繁体   English   中英

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

[英]How to correctly make a Wordpress plugin returns a downloadable excel file

我正在尝试为我的wordpress插件制作一些报告。 此报告必须可以作为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()必须放在第一个标头之前(来自Wordpress的核心文件)。 如果可能的话,我不想修改核心文件。

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

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

任何帮助赞赏!

由于header()已经在menu-header.php中发送,因此发送标题太迟了。 从提供的代码我无法看到你在哪个点发送头文件,但是一个好的地方就是在plugins_loaded动作中,因为当所有插件都已加载时,在发送任何输出之前调用该动作钩子。

下载链接如下所示:

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

而且,plugins_loaded动作:

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();      
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM