Php DOMPDF不';如果HTML已经存在,则无法工作

Php DOMPDF不';如果HTML已经存在,则无法工作,php,html,pdf,dompdf,Php,Html,Pdf,Dompdf,我有一个函数,它使用DOMPDF生成一个.pdf,其中包含我为$html参数设置的内容 function generate_pdf($html){ //DOMPDF stuff } 这是可行的,但我遇到的问题是,当我从一个已经有HTML内容的页面调用这个函数时,它失败了 失败 <?php require_once '../header.php'; //This has HTML content in it. $html = '<h1>stuff</h1&

我有一个函数,它使用DOMPDF生成一个.pdf,其中包含我为$html参数设置的内容

function generate_pdf($html){
    //DOMPDF stuff
}
这是可行的,但我遇到的问题是,当我从一个已经有HTML内容的页面调用这个函数时,它失败了

失败

<?php
  require_once '../header.php'; //This has HTML content in it.
  $html = '<h1>stuff</h1>';
  generate_pdf($html);
?>

请注意,此函数所在的文件有一个名称空间,这就是为什么
$dompdf=new\dompdf\dompdf()可能出现错误,但该行运行正常。

在将完整代码添加到问题后更改了答案:

我在包含的文件中有完整的HTML内容,前后没有额外的HTML(也没有php回音)

我以前犯过一个错误——我混淆了dompdf自动加载和内容的包含——但请看下面在我的案例中它是如何工作的。这是一个php文件的内容,没有函数:

<?php
require_once '../../dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->set_option('isPhpEnabled', true);
ob_start();

//Here I am getting a few variables (from the URL via GET) which I use in the included php file 

include_once "your_content_in_one_file.php";
$html = ob_get_contents();
ob_end_clean();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream($pdf_name);
?>  

它最终与以下事实有关:
ob_start()已在系统中的其他位置调用。使用

if (ob_get_level()){
    ob_end_clean();
}

修正了我的问题。希望它能帮助其他人。

也许这是我的问题。如果HTML出现在前后(想想包含的页眉和页脚),这会导致问题吗?我想是的。你应该在一个额外的php文件中组装/组合完整的HTML,并将其包括在内。我刚刚做了另一个测试并更新了我的问题。在我的函数中,我已经从
require\u once-DOMPDF\u-PATH更改了/autoload.inc.php'
包含一次DOMPDF\u路径/autoload.inc.php'。但是,函数调用之前的HTML(或其他任何内容)仍然使我无法流式传输已经发送的pdf:Header。所以,我不认为问题出在HTML之后。明白我的意思了吗?但这意味着你不应该在该文件中有任何HTML输出,包括之前和之后都不应该有-甚至没有像
之类的空标记,也没有php echoing.idk。。。。当我做
$html='stuff'生成pdf($html)在我调用函数的文档主体中,它在生成的.pdf文件中包含了所有类型的头HTML内容(在使用Notepad++检查时)。但这会导致.pdf被损坏。
function generate_pdf($html){
    //Get the necessary dompdf files
    include_once DOMPDF_PATH . '/autoload.inc.php';

    // instantiate and use the dompdf class
    $dompdf = new \Dompdf\Dompdf();
    $dompdf->loadHtml($html);

    // Render the HTML as PDF
    $dompdf->render();

    //Output the PDF
    $dompdf->stream();  
}
<?php
require_once '../../dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->set_option('isPhpEnabled', true);
ob_start();

//Here I am getting a few variables (from the URL via GET) which I use in the included php file 

include_once "your_content_in_one_file.php";
$html = ob_get_contents();
ob_end_clean();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream($pdf_name);
?>  
if (ob_get_level()){
    ob_end_clean();
}