6

Okay, so maybr I'm going about doing this entirely wrong, I probably am. But I would like to be able to take the HTML between a ... like so:

$str = ?>
... some HTML goes here ...
<?php ;

Am I completely off my rocker to think I can do this? I couldn't think of a way to put it into words so I could search it on Google, which is why I'm here...

4 Answers 4

9

You can use output buffering:

ob_start();
?>
... some HTML goes here ...
<?php
echo 'php outputs are captured too';
$str = ob_get_contents();
ob_end_clean();

Alternatively, if it's just a little bit of HTML (and no php code within), just write it down with one of the string formats like heredoc or nowdoc:

$str = <<<'NOWDOC'
... some HTML goes here
NOWDOC;
Sign up to request clarification or add additional context in comments.

1 Comment

Works beautifully! I'm working with a MVC framework (symfony) and trying to keep to the rules and this makes things easier, for sure. AND Komodo will format the HTML this way! Thanks!!
6

Look into heredocs and nowdocs. A heredoc looks like:

$str = <<<HTML
  <div>This is some text!</div>
HTML;

// We're back in PHP.
echo $str;

If you specifically want to work with HTML, look into XHP.

1 Comment

Thanks for your answer! I haven't ever heard of XHP, it seems really interesting and useful. I think I'll install and play around with it. ^_^ It's awesome what Facebook is opening up to the OSS community. I've used Cassandra and Tornado, myself.
1

Just wanted to add to phihag's answer.

It is possible to capture HTML with a function as well, including with anonymous functions:

<?php $bob = function() { ?>
... some HTML here...
<?php }; ?>

and later output $bob:

<?php $bob(); ?>

or capture the output of $bob somewhere else with output buffering:

ob_start();
$bob();
$str = ob_get_contents();
ob_end_clean();

Comments

0

PHP has a multiline, specially delimited string for such situations.

This talks about it a little.

1 Comment

Thanks for your answer! I tried heredoc, but it didn't like the PHP sitting in it for some reason. It recognized it correctly because it threw the exception set in the class's __get() when a method isn't found.

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.