内联 php 脚本变量在 DOMPDF 中不起作用

inline php script variables not working in DOMPDF

当我生成 pdf 时,内联 php 脚本没有执行,只有 html 部分被打印在 pdf 上。我已经设置了 $isPhpEnabled =True 。

<?php
// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$abc="This is the php text";
$html = <<<'ENDHTML'
<html>
<head>
<style>
h1{color:#555555;width:100%;border-bottom:2px solid powderblue;}
</style>
</head>
 <body>
  <h1 >Name : <script type="text/php"> echo $abc; </script></h1>
 </body>
</html>
ENDHTML;
$dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

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

// Output the generated PDF to Browser
$dompdf->stream("dompdf_out.pdf", array("Attachment" => false));
exit(0);
?>

尝试

<?php
// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$abc="This is the php text";
$html = "
<html>
<head>
<style>
h1{color:#555555;width:100%;border-bottom:2px solid powderblue;}
</style>
</head>
 <body>
  <h1 >Name : $abc</h1>
 </body>
</html>
";
$dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

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

// Output the generated PDF to Browser
$dompdf->stream("dompdf_out.pdf", array("Attachment" => false));
exit(0);
?>

诀窍就是将 html 呈现为 php 中的字符串,并与您希望在 PDF 中显示的值连接起来。 你必须小心引号,因为你的标记中会有双引号。因此,如果您明白我的意思,使用单引号作为包装器会有所帮助。

所以像这样:

$html = '<div class = "some class" >' . $variable . '</div>';

然后您可以将此字符串加载到您的 $dompdf 实例中。 $variable 可以从任何地方提取它的值,例如数据库,或者您可以通过循环迭代来构建布局元素。