Home > other >  Call PHP variable in HTML
Call PHP variable in HTML

Time:12-27

I wrote a code involving nested PHP and HTML parts as below. Why variable "v" is not displayed, But the variable "u" is?

<?php

$v= rand (1,15);
$u= rand (1,15);

$h = <<<EOD
            <!DOCTYPE html>
            <html>
            <body>
                    <p style="margin-top:80px">This is a random number:</p>
                    <?php echo $v ?>
            </body>
            </html>
EOD;
            echo $h;

?>

<html>

    <body>
        u=<?php echo $u ?>
    </body>

</html>

CodePudding user response:

PHP has two modes.

  1. Inside <?php...?> (and other PHP tags) PHP code is evaluated
  2. Outside those tags, code is streamed directly to the output

You have <?php echo $v ?> inside a PHP section (inside a string created with HEREDOC).

It doesn't trigger PHP evaluation of the content when the string is created because it is just part of the string. It doesn't trigger PHP evaluation when you later echo it because you are just echoing a string.

<?php echo $v ?> will be in the (invalid) HTML sent to the browser, and the browser will treat it as an unknown tag. The value of $v will be one of the attributes. The browser won't render anything for this unknown tab, but you will be able to see it in the Developer Tools Inspector or with View➝Source


Rethink your application design. Don't try to store strings containing PHP code. Generate the string with the data you need in it in the first place.

$h = <<<EOD
            <!DOCTYPE html>
            <html>
            <body>
                    <p style="margin-top:80px">This is a random number:</p>
                   $v
            </body>
            </html>
EOD;
            echo $h;
  • Related