使用mpdf生成每周报告pdf - functions.php

时间:2017-01-20 14:35:04

标签: php wordpress pdf mpdf

我在wordpress上使用mpdf来生成PDF文件。我正在处理一项功能,该功能会向我的用户发送每周报告,该报告应作为电子邮件发送,pdf将附在电子邮件中。

我的问题是我在functions.php文件中运行代码,因为为了每周运行这段代码,我将使用服务器端cron作业,我的函数应该在functions.php文件中执行它。所以我在functions.php文件中添加了这段代码:

function weeklyReportFunc(){
    include('mpdf/mpdf.php');
    $mpdf = new mPDF();
    ob_start();
    require get_template_directory() . '/includes/report.php';
    $x = ob_get_contents();
    ob_end_clean();
    $mpdf->WriteHTML($x);
    $today = date('Y-m-d');
    $pdfName = 'weekly-report-'.$today;
    $mpdf->Output($pdfName.'.pdf', 'D');
}

这显示我的错误:

Warning: Cannot modify header information - headers already sent by (output started at 
/home/user/public_html/doms/wp-admin/includes/template.php:1995) in /home/user/public_html/
doms/wp-content/themes/mytheme/mpdf/mpdf.php on line 8314

Warning: Cannot modify header information - headers already sent by (output started at 
/home/user/public_html/doms/wp-admin/includes/template.php:1995) in   
/home/user/public_html/doms/wp-content/themes/mytheme/mpdf/mpdf.php on line 1706
mPDF error: Some data has already been output to browser, can't send PDF file

我该如何解决这个问题?也许我需要在某些动作中使用我的功能?但是哪一个?有什么想法吗?

2 个答案:

答案 0 :(得分:1)

终于找到了解决方案。所以我在我的主题文件夹中创建了一个php文件,并在文件的最顶部添加了require('../../../wp-load.php');代码,这使得所有的wordpress函数都可用,即使这个文件不是wordpress模板页面。因此,现在所有函数都在此文件中可用,我将我的代码从functions.php文件移动到此文件,并且我已经在此文件上运行了cron作业。希望这会有助于其他人。

答案 1 :(得分:0)

使用$x report.php 输出缓冲区保存到exec()

function weeklyReportFunc(){
    ob_start();
    include('mpdf/mpdf.php');
    $mpdf = new mPDF();
    exec('php -f '.get_template_directory().'/includes/report.php',$output);
    $x = $output[0];
    $mpdf->WriteHTML($x);
    $today = date('Y-m-d');
    $pdfName = 'weekly-report-'.$today;
    $mpdf->Output($pdfName.'.pdf', 'D');
}
相关问题