-->

How to use php variable inside pdf ->page_script()

2019-07-24 13:24发布

问题:

How to use PHP variable inside $pdf->page_script(); Here is my code

<?php
<script type="text/php">
$pdf->page_script(\'
    if ($PAGE_NUM >= 2) {$pdf->image($var,"jpg",25,500,0,0);
    }
  \');

</script>

?>

I am getting an error Syntax error in $var.

回答1:

Inline script is run via the eval() function and any variables declared in the global scope are only accessible via the $GLOBALS superglobal ($GLOBALS['var']) or by initializing them with the global keyword (global $var).

I should note that if you're using dompdf 0.6.x you no longer have to specify the image type. You also appear to have the parameters backwards. The method looks for image path, x, y, width, then height.

The following should work:

<?php
<script type="text/php">
  $pdf->page_script('
    if ($PAGE_NUM >= 2) {
      $pdf->image(' . $GLOBALS['var'] . ',0,0,25,500);
    }
  ');
</script>
?>

Minor note: Since you're creating a page script I concatenated the image path variable with the rest of the script string. You can include that variable reference as part of the script rather than concatenate, but then you're performing additional look-ups on the variable every time the script is run. Though I must admin this is a minor performance consideration in the grand scheme of where this is running.



标签: php dompdf