I have some HTML that I need to sometimes wrap in an anchor tag when a condition is met. I could do something like this:
<?php
$html = '<div>my html</div>';
if ($condition):
?>
<a href="http://google.com"><?php echo $html ?></a>
<?php else: ?>
<?php echo $html ?>
<?php endif; ?>
…but I don’t want to have to wrap my html in quotes to turn it into a string. This is for two reasons: syntax highlighting goes away, and its harder to maintain.
How can I do something like the following?
<!-- pseudo code -->
<?php if ($condition): echo $this->wrapWithLinkTo('http://google.com', ?>
<div>my html</div>
<?php ); endif; ?>
…so that the end result would be:
<!-- when $condition is true -->
<a href="http://google.com"><div>my html</div></a>
<!-- when $condition is false -->
<div>my html</div>
Use Output buffering!
PHP’s output buffering is used to capture output from PHP code, HTML mode, or anything, and then either store it to a variable and not output it to the client (ob_get_clean()), store it into a variable and also send it to the client(ob_get_flush()), or do a whole bunch of other things with it! (ob_* functions)