David David - 1 month ago 18
HTML Question

Not able to use if statement with dompdf

This is my code:

<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();

$stmt = $pdo->prepare('SELECT name FROM my_table');
$stmt->execute();

$results = $stmt->fetchAll();
foreach( $results as $row ) {
$dompdf = new DOMPDF();

$html = "

".if(!empty($row['name'])) {
echo "My name is".$row['name']."";
}."

";

$dompdf->load_html($html);
}
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream();
?>


I'm always getting:


Parse error: syntax error, unexpected 'if' (T_IF) in
/var/www/user_name/html/create_pdf.php on line 17


Simple HTML code like this
$html = "<p>Hello, it's me!</p>";
works.

Also PHP code like this
$html = "My name is ".$row['name']."!";
works.

Just the if-statement seems not to work.

What am I doing wrong?

Answer

You can't concatenate strings with if in the middle (because the if statment doesn't return anything).

You can solve this by using the ternary operator:

$html = "
    ".(!empty($row['name']) ? "My name is".$row['name'] : '')."
";

In case you have long if-else statements you should close the string and concatenate it inside:

$html = "";
$html .= "Some string\n";
if (....) {
    $html .= "Something new\n";
} elseif (...) {
    $html .= "more...\n";
} else {
    $html .= "...\n";
}
$html .= "Some text\";