Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing HTML to a string in PHP

Tags:

php

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...

like image 693
Logan Bibby Avatar asked Feb 22 '11 22:02

Logan Bibby


People also ask

Why use htmlspecialchars in PHP?

The htmlspecialchars() function converts special characters into HTML entities. It is the in-built function of PHP, which converts all pre-defined characters to the HTML entities.

How to strip HTML tags from string in PHP?

PHP provides an inbuilt function to remove the HTML tags from the data. The strip_tags() function is an inbuilt function in PHP that removes the strings form HTML, XML and PHP tags. It accepts two parameters. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str.


2 Answers

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;
like image 196
phihag Avatar answered Sep 30 '22 16:09

phihag


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.

like image 28
ide Avatar answered Sep 30 '22 18:09

ide