Is it possible to output something like <h3>Something</h3>
in PHP without using echo? Say I had one class file for displaying information from a database, but I wanted it to be pure PHP and no large echo statements in there. Could I do this or do I need to use echo
thanks
Try closing and re-opening PHP tag some that:
# PHP CODE
?>
<h3>Something</h3>
<?php
#MORE PHP CODE
There are quite a few ways, print()
- die()
- exit()
, HTML, heredoc
and nowdoc
:
<?php
print("<h3>Something</h3>");
and
<?php
die("<h3>Something</h3>");
and
<?php
exit("<h3>Something</h3>");
and good 'ol HTML
<!doctype html>
<head></head>
<body>
<?php
// some code
?>
<h3>Something</h3>
<?php
// some other code
?>
</body>
</html>
Edit: Plus, as sudo.ie
states in an answer, using heredoc.
There is also nowdoc which lets you do stuff like, and taken from example #6:
<?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
public $foo;
public $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>
This is maybe what you are looking for, using a heredoc:
<?= <<<EOT
<h1>
This is some PHP text.
It is completely free
I can use "double quotes"
and 'single quotes',
plus $variables too, which will
be properly converted to their values,
you can even type EOT, as long as it
is not alone on a line, like this:
</h1>
EOT;
?>