8

I was wondering, mostly because I think I've seen it before somewhere, if it is possible to store HTML within a variable, something like the following (I know this makes no sense, it's just to clarify my question):

<? $var = ' ?>
text goes here
<? '; ?>

And then $var would equal text goes here

6
  • 1
    If possible you should avoid this. Embed PHP into HTML not vice versa. Commented Jun 9, 2011 at 13:54
  • "Embed PHP into HTML not vice versa." O RLY? Commented Jun 9, 2011 at 13:58
  • @Felix Kling: why would you recommend Embedding PHP into HTML and not vice versa? Commented Jun 9, 2011 at 14:01
  • @Nightwolf: Because creating endless HTML strings is error prone (e.g. escaping of quotes). You will most likely also loose syntax highlighting if you use an IDE. Granted, with heredoc it might not be that bad, but there is barely a reason to not write HTML the "normal" way and just echo the data where it should be. It is a better separation of logic and presentation. Commented Jun 9, 2011 at 14:05
  • @Felix Kling, what I want to use this for is for newsletter templates that require a php configuration for my system as well as a HTML template. I'd like these two to be included in the same php file without losing my HTML syntax coloring. I figured this was a great solution. Commented Jun 9, 2011 at 14:26

3 Answers 3

16

You could do that using output buffering. Have a look at the examples at ob_get_contents() and ob_start().

<? ob_start(); ?>

All kinds of stuff, maybe some <?= "php"; ?> etc.

<? $var = ob_get_contents(); ?>
Sign up to request clarification or add additional context in comments.

3 Comments

This is the one I was looking for, heredoc solves my problem as well but leaves the code colored like php in Dreamweaver which was one of the reasons I wanted this.
One thing is also needed though, without ob_end_clean(); the original HTML will still be outputted.
Or even you can just use ob_get_clean() instead of doing ob_get_contents() + ob_end_clean()
6

You may be thinking of the Heredoc syntax:

<?php
$var = <<<EOD
text goes here
EOD;
?>

4 Comments

Note that this will generate the string "\ttext goes here\n\t". Be careful of whitespace.
The trailing EOD should not be indented, it should be on the first column. Also, this way the text will contain spaces in front.
@Eric Good point. I edited out the tabs, though (thanks for your initial edit - I forgot) since the EOD; must (AFAIR) be at the start of the line.
@Blagovest Buyukliev Yes, this was due to an edit collision :)
0

Check out this facebook blog post on XHP, a language that allows XML literals within PHP code.

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.