David David - 1 year ago 99
HTML Question

Not able to use if statement with dompdf

This is my code:

$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');

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

$html = "

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


$dompdf->setPaper('A4', 'portrait');

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>";

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

Just the if-statement seems not to work.

What am I doing wrong?

Answer Source

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\";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download