无法修改标头信息-/wp-includes/formatting.php:5716

问题描述

我创建了一个自定义导出到Excel函数,以导出在自定义页面中针对自定义帖子类型生成的报告。

在函数中,我使用了以下headers

    if(isset($_GET['excelexport'])) {
        header("Pragma: public");
        header("Expires: 0");
        header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
        header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
        header("Content-Disposition: attachment; filename=\"report.xlsx\";" );
        header("Cache-Control: private",false);
        header("Content-Transfer-Encoding: binary");        
        exportToExcel();

    }

但是我不断收到错误消息:

警告:无法修改标头信息-标头已发送(输出始于 /home/user/public_html/wp-includes/formatting.php:5716)中 /home/user/public_html/wp-content/themes/twentyseventeen/inc/userHistory.php,第36行

我用谷歌搜索了一个解决方案,但是没有帮助。

解决方法

该错误意味着,当代码到达该点时,您已经有了Wordpress自己在其他地方调用的其他标头(...)。如果您想在此之前放弃输出并与您一起使用,则可以执行以下操作:

if(isset($_GET['excelexport'])) {
   

 ob_end_clean(); // Discard all the output generated until this point
        header("Pragma: public");
        header("Expires: 0");
        header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
        header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
        header("Content-Disposition: attachment; filename=\"report.xlsx\";" );
        header("Cache-Control: private",false);
        header("Content-Transfer-Encoding: binary");        
        exportToExcel();

    }

这应该可以并消除错误

,

请确保您的代码将在wordpress生成的任何输出之前执行。

在您的functions.php中尝试一下:

add_action('init','my_excel_output');

function my_excel_export() {
    
    if( isset( $_GET['excelexport'] ) ) {
        header("Pragma: public");
        header("Expires: 0");
        header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
        header("Cache-Control: must-revalidate,false);
        header("Content-Transfer-Encoding: binary");        
        exportToExcel();        
        wp_die();
    }
}

输出excel数据后,应使用wp_die()停止wordpress执行

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...