0

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?

2 Answers2

1
$html = "text... " . (!empty($row['...'])) ? $row['...'] : " " . " more text...";

Remove the if and create an 'inline' or ternary expression like above.

If statements cannot be concatenated unless a shorthand expression is used (ie: ternary)

In your case, this should work:

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

For longer concatenation, you can do this (and readability):

$html = "";
$html .= (expression) ? True : False;
$html .= "";

To concatenate we use .= in PHP.

I'd suggest using the print_f() method in PHP for long HTML, something like.

print_f("your name is %s", (!empty($row['name'])) ? $row['name'] : 'Default');
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
0

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\";
Dekel
  • 60,707
  • 10
  • 101
  • 129
  • Thanks it's working. But, what if I have (big) if-else-statements or so. Is there a more elegant solution for it? –  Oct 20 '16 at 18:25