I am using DOMPDF to enable users to save single pages as PDFs.
This is a bilingual website (German/English). At the top of the body
tag of the generated page, I use the following code (mostly copied from dompdf example files), which contains an if/else clause to generate automated page numbers on top of each page either in German or in English:
<script type="text/php">
if ( isset($pdf) ) {
// v.0.7.0 and greater
$x = 36;
$y = 24;
if($lang == "de") {
$text = "Seite {PAGE_NUM} von {PAGE_COUNT}";
} else {
$text = "page {PAGE_NUM} of {PAGE_COUNT}";
}
$font = $fontMetrics->get_font("helvetica", "regular");
$size = 6;
$color = array(0,0,0);
$word_space = 0.0; // default
$char_space = 0.0; // default
$angle = 0.0; // default
$pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
}
</script>
So the output should either be "Seite X von X" or "page X of X", depending on the value of $lang
.
Before that, I am defining the $lang
variable depending on the user's browser settings with a similar if/else clause either as "de" (German) or "en" (English, if the browser language is NOT German) and use that as a condition to decide whether the contents are output in German or English.
Further down in the code this works as intended (using PHP conditions). Only that automated pagination in the code above doesn't seem to recognize the $lang
variable - the output is always in English.
But it is printed, which shows that the PHP code is parsed.
My question is: Why is the $lang
variable not recognized in that part of the code, and what could I do to make it work?
Thanks to the two comments by @Nick and @proprit I was led to the issue of scope - that's what caused the problem. I found out that if I add global $lang;
before the condition, it works properly. So the code has to be:
<script type="text/php">
if ( isset($pdf) ) {
// v.0.7.0 and greater
$x = 36;
$y = 24;
global $lang;/* this is the only thing I added */
if($lang == "de") {
$text = "Seite {PAGE_NUM} von {PAGE_COUNT}";
} else {
$text = "page {PAGE_NUM} of {PAGE_COUNT}";
}
$font = $fontMetrics->get_font("helvetica", "regular");
$size = 6;
$color = array(0,0,0);
$word_space = 0.0; // default
$char_space = 0.0; // default
$angle = 0.0; // default
$pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
}
</script>
Thanks for the help!