Adam Hunter Peck
Adam Hunter Peck

Reputation: 317

PHP - can a long string of HTML be wrapped in a PHP variable?

Can this be done - opening a variable with one PHP tag, then closing the PHP tag but keeping the variable open so everything beneath becomes the value of the variable? Or is there a limit on PHP variable size / characters?

<?php $content = " ?>

a bunch of content goes here <br />
with lots of HTML tags and JS scripts

<?php "; ?>

Upvotes: 4

Views: 18850

Answers (7)

markus
markus

Reputation: 40695

What your code would do is to store a string starting with ?> and ending with <?php in the variable $content. That's probably not what you want to do? If you later echo such a string, you would most probably get errors due to these php tags.

As mentioned in other answers, heredoc would be a solution but in general you should try to avoid such situations where you have to store very long html sequences in a variable. Rather use a view file and inject some dynamic content there or use some sort of include.

So, depending on what you really want to do,your options are:

  1. heredoc
  2. $content = "<html>markup here</html>";
  3. via output buffering
  4. using a view (look for info about the MVC pattern, you can also just do VC for a start)
  5. using includes

Upvotes: 4

werd
werd

Reputation: 646

$content = 'large amount of text';
or
$content = 'text';
$content .= 'other text';
$content .= 'end text';

Upvotes: 2

Gordon
Gordon

Reputation: 317147

You can either use HEREDOC/NOWDOC

$content = <<< 'HTML'

a bunch of content goes here <br />
with lots of HTML tags and JS scripts

HTML;

or output buffering, e.g.

<?php ob_start(); ?>

foo

<?php
    $var = ob_get_clean();
    var_dump($var); // will contain foo and surrounding whitespace

Upvotes: 10

codaddict
codaddict

Reputation: 455340

Yes you can do it.

A closing tag inside double quotes as : " ?>" will not be treated specially. They are just string contents.

is there a limit on PHP variable size / characters?

No. You can stuff as much as you can into a variable till your memory is full.

Upvotes: 0

Piotr Pankowski
Piotr Pankowski

Reputation: 2406

try:

<?php ob_start (); ?>

.... html

<? 
$content = ob_get_clean (); 
?>

See http://pl.php.net/manual/en/book.outcontrol.php for details

Upvotes: 1

Fanis Hatzidakis
Fanis Hatzidakis

Reputation: 5340

No, but you can probably do some of it with heredoc

$content = <<< END
some content here<br/>
<script type="text/javascript">
alert('hi');
</script>

END;

Upvotes: 7

Related Questions