0

Is it possible to declare a variable value like or something similar:

<?php
    $var =
?>

<!-- block of html code that goes into $var -->

<?php
    //do anything with $var that contains the html code of above
?>
7
  • 4
    Answer is yes, you can use. But before ask, you could easily check with echo $var; at second part of php! Commented Apr 9, 2014 at 13:05
  • But I'm getting Parse error: syntax error, unexpected '?> ' in index.php on line 8. Commented Apr 9, 2014 at 13:08
  • You're looking for either a heredoc or nowdoc. Commented Apr 9, 2014 at 13:09
  • 1
    This error not about using $var, it is about your opening closing php tags. If you want to use $var inside of html,not php, you should write <?php echo $var; ?> inside of html after declaring of $var. Commented Apr 9, 2014 at 13:13
  • 1
    @KidDiamond how is php supposed to know where that html content ends? The error you mentioned shows that this is not possible that way, better read a separate html file into the variable with file_get_contents or something like that. Code between <php? and ?> is understood by the parser to be php, code outside that is not. Commented Apr 9, 2014 at 13:18

2 Answers 2

3
<?php
ob_start();
?>
<!-- block of html code that goes into $var -->
<?php
$var = ob_get_contents();
while (@ob_end_flush());

Note this assumes you are not already using output buffering.

Sign up to request clarification or add additional context in comments.

Comments

0

No this is not possible.

You can declare a variable in a php-block, then have that block terminate then some html part and then another php block and use it there.

But you cannot declare a variable like this, assigning the subsequent html contents to it.

But what you can do, as pointed out in Anders J's answer you can do the opposite, assign preceding contents to a variable. But note that there are some possible pitfalls.

Php is parsed by identifying the <?php ?> block first, everything outside of that is ignored by the parser, so in order to do this you would better have that html content in a separate file and read it into your variable using something like file_get_contents.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.