我有一个 php 文件 myfile.php
,里面基本上有很多 html 和一些 php 代码,例如:
<body>
Name: <?php echo $_GET['id'] ?>
<!-- and so on ... -->
</body>
我正在使用用 PHP 编写的开源 HTML 到 PDF 转换器,它需要输入要转换的 html 内容:
PDFConverter::convertHTMLToPDFFIle($html_input, $filename_output_pdf);
如何将 myfile.php?id=XX
生成的 html 提供给 $html_input
?
您可以使用一点输出缓冲并包含它。
<?php
ob_start();
include "myfile.php";
$content = ob_get_clean();
// $content now contains the processed code of myfile
此时,文件内容已由 PHP 处理,因为包含并在 $content
变量中。您可以将其传递给您的 convertHTMLToPDFFile()
方法。
PDFConverter::convertHTMLToPDFFile($content, $outFilename);
编辑:OP 编辑问题添加要求,即包含的文件需要能够接受变量。
当包含/需要文件时,它会继承当前作用域。这意味着它可以访问任何已定义的变量、类定义、函数等。因此,在包含文件之前确定共享哪些变量并设置这些值。例如:
<body>
Name: <?php echo $id; ?>
<!-- and so on ... ->
</body>
然后……
<?php
ob_start();
$id = <whatever the value should be>;
include "myfile.php";
$content = ob_get_clean();