>我正在使用mPDF类从PHP文件中输出PDF数据。我需要遍历 SQL Server 查询,另存为新变量并写入$html以便可以将其输出到 pdf 中。我不能把它放在WriteHTML函数中,因为它不能识别PHP代码。我需要整个数组的内容,所以我不能只打印一个变量。
我有两个文件:
pdf-test.php
:
此文件从包含的其他 php 文件中收集会话变量并重新分配它们,因此我可以在$html中使用它们。
<?php
// Include files
require_once("form.php");
require_once("configuration.php");
session_start();
$html = '
<h3> Form A </h3>
<div>
<table>
<thead>
<tr>
<th colspan="3">1. Contact Information</th>
</tr>
</thead>
<tr>
<td> First Name: </td>
<td> Last Name: </td>
</tr>
<tr>
<td>'.$firstName.'</td>
<td>'.$lastName.'</td>
</tr>
.
.
.
</table>
';
echo $html;
pdf-make.php:这个文件包含代码,以实际将pdf-test.php的内容转换为pdf。
<?php
// Direct to the mpdf file.
include('mpdf/mpdf.php');
// Collect all the content.
ob_start();
include "pdf-test.php";
$template = ob_get_contents();
ob_end_clean();
$mpdf=new mPDF();
$mpdf->WriteHTML($template);
// I: send the file inline to the browser.
$mpdf->Output('cust-form-a', 'I');
?>
这是我的循环:
$tbl = "form_Customers";
$sql = "SELECT ROW_NUMBER() OVER(ORDER BY custFirt ASC)
AS RowNumber,
formID,
custFirt,
custLast,
displayRecord
FROM $tbl
WHERE formID = ? and displayRecord = ?";
$param = array($_SESSION["formid"], 'Y');
$stmt = sqlsrv_query($m_conn, $sql, $param);
$row = sqlsrv_fetch_array($stmt);
while ($row = sqlsrv_fetch_array($stmt)) {
$rowNum = $row['RowNumber'];
$firstN = $row['custFirt'];
$lastN = $row['custLast'];
}
当我尝试在$html中包含$rowNum、$firstN或$lastN时,例如
<td> '.$rowNum.'</td>
,它只是显示为空白。我不确定循环应该去哪里(哪个文件(或如何像其他变量一样在$html中包含$rowNum、$firstN和$lastN变量。
我是PHP的新手(一般的编码相对较新(,我没有太多使用它的经验,但是我已经能够在不包含查询的情况下使mPDF在类似实例中为我工作。
任何帮助将不胜感激。非常感谢!
我不确定您的循环如何与其他两个文件交互,但这对我来说看起来过于复杂。我会在一个.php
文件中解决这个问题,有点像这样:
<?php
//Include Files
include('mpdf/mpdf.php');
... //Your additional includes
//Define a row template string
$rowtemplate =<<<EOS
<tr>
<td>%%RowNumber%%</td>
<td>%%custFirt%%</td>
<td>%%custLast%%</td>
</tr>
EOS;
//Initialize the HTML for the document.
$html =<<<EOS
<h3> Form A </h3>
... //Your code
<td> Last Name: </td>
</tr>
EOS;
//Loop Code
$tbl = "form_Customers";
... //Your code
$row = sqlsrv_fetch_array($stmt);
while ($row = sqlsrv_fetch_array($stmt)) {
//Copy rowtemplate to a temporary variable
$out_tmp = $rowtemplate;
//Loop through your SQL variables and replace them when they appear in the template
foreach ($row as $key => $val) {
$out_tmp = str_ireplace('%%'.$key.'%%', $val, $out_tmp);
}
//Append the result to $html
$html .= $out_tmp;
}
// Close the open tags in $html
$html .= "</table></div>";
//Write the PDF
$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->Output('cust-form-a', 'I');
我正在对字符串使用 heredoc 语法,因为我认为这是包含大字符串的最干净方法。
另外,我更喜欢省略结束?>
标签,因为它引入了愚蠢的错误来源。