Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

martinszeltins's avatar

How could I not have HTML code in my PHP logic when working with templates?

I am generating a PDF file from HTML. I have most of my HTML structure in a separate file called invoice.html but the loop to generate table rows is in my PHP logic. Is there a way to not have it in my PHP so I don't mix HTML with PHP together?

invoice.html

<h1>Hi, {client.name}!</h1>
<p>You have {sum} to pay until {due.date}</p>

Here is the summary
<table>
    {table.rows}
</table>

<p>Thanks, {sender.name}<p>
<p>{issue.date}</p>

createPDF.php

$table_rows = '';
foreach ($datas as $data) {
    $table_rows .= '<tr><td>' . $data->details . '</td></tr>';
}

$invoice_html = file_get_contents( 'invoice.html' );

$invoice_html = str_replace('{client.name}', $client_name, $invoice_html);
$invoice_html = str_replace('{table.rows}', $table_rows, $invoice_html);
...

$pdf = DomPDF::loadHTML( $invoice_html );
return $pdf->download( 'invoice.pdf' );
0 likes
1 reply

Please or to participate in this conversation.