49

Im new to PHP and I can't figure out what the rules are for using the echo function. For example, if I need to echo a large block of css/js, do I need to add echo to each line of text or is there a way to echo a large block of code with a single echo?

When I try to echo a big block of code like this one, I get an error:

if (is_single()) {
echo '<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css"> 
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}

.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style> 

<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" /> 
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script> 
<script src="http://jotform.com/js/location.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script> 
<script type="text/javascript"> 

JotForm.init(function(){
$('input_6').hint('ex: [email protected]');
});
</script>';
}else {

}

Is there a better way to echo large blocks of code without a lot of work (adding echo to each line for example)?

11 Answers 11

144

Heredoc syntax can be very useful:

// start the string with 3 <'s and then a word
// it doesn't have to be any particular string or length
// but it's common to make it in all caps.
echo <<< EOT
    in here is your string
    it has the same variable substitution rules
    as a double quoted string.
    when you end it, put the indicator word at the
    start of the line (no spaces before it)
    and put a semicolon after it
EOT;
5
  • 8
    I'm not a fan of heredoc syntax, but I give you a +1 because you're the first one to actually illustrate what heredoc syntax is here, making it a useful answer. Commented Apr 20, 2010 at 5:13
  • 1
    @thomasrutter - I also am not a huge fan of it: many IDEs don't deal with it well, and it either stuffs up your code indentation or you get a string with a ton of useless whitespace.
    – nickf
    Commented Apr 20, 2010 at 7:34
  • points to note: if you use Eclipse (with PDT) to develop PHP, you will find that heredoc has incorrect code highlighting.
    – Raptor
    Commented Sep 3, 2012 at 3:01
  • sometimes you need to return a large string instead of echo. an example will be WordPress shortcode functions. Heredoc is helpful in some scenarios, specially parsing many variables within huge string blocks.
    – Codex73
    Commented Jul 15, 2013 at 17:36
  • 3
    Does not work for me, i get this error: Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or heredoc end (T_END_HEREDOC) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in C:\xampp\htdocs\mbcl\test.php on line 256 Edit: Solved, the EOT has to be at the start of the line, no intendation allowed, the only other allowed char in the line is the semikolon after EOT.
    – Black
    Commented Sep 23, 2015 at 7:00
74

One option is to get out of the php block and just write HTML.

With your code, after the opening curly brace of your if statement, end the PHP:

if (is_single()) { ?>

Then remove the echo ' and the ';

After all your html and css, before the closing }, write:

<? } else {

If the text you want to write to the page is dynamic, it gets a little trickier, but for now this should work fine.

6
  • 8
    -1 This makes the code hard to read and prone to errors, and should definitely be avoided. Heredoc syntax, as mentioned by @nickf is the way to go.
    – laurent
    Commented Jun 11, 2014 at 19:58
  • 6
    But it is a possible solution, so why -1?
    – Black
    Commented Sep 23, 2015 at 6:52
  • 6
    A solution is a solution.
    – Black
    Commented Jan 20, 2017 at 16:03
  • 5
    I feel many here, all too many, are a little trigger-happy when it comes to the downvote button. Commented Oct 22, 2017 at 18:58
  • 2
    I'm a ASP.NET guy by day, and a longtime PHP guy by night.. and had gotten a little rusty over the years with .NET taking over my life more recently.. and totally forgot I can just do straight HTML to the output stream.. no PHP tags at all in my index.php .. feeling silly for needing S.O. to remind me. My vote goes to the simplest answer.
    – bkwdesign
    Commented Mar 26, 2018 at 12:10
22

Check out heredoc. Example:

echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

echo <<<"FOOBAR"
Hello World!
FOOBAR;

The is also nowdoc but no parsing is done inside the block.

echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
1
  • I was looking for this!
    – MUHINDO
    Commented Apr 24, 2022 at 8:00
7

Echoing text that contains line breaks is fine, and there's no limit on the amount of text or lines you can echo at once (save for available memory).

The error in your code is caused by the unescaped single quotes which appear in the string.

See this line:

$('input_6').hint('ex: [email protected]');

You'd need to escape those single quotes in a PHP string whether it's a single line or not.

There is another good way to echo large strings, though, and that's to close the PHP block and open it again later:

if (is_single()) {
  ?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css"> 
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}

.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style> 

<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" /> 
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script> 
<script src="http://jotform.com/js/location.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script> 
<script type="text/javascript"> 

JotForm.init(function(){
$('input_6').hint('ex: [email protected]');
});
</script>
  <?php
}else {

}

Or another alternative, which is probably better for readability, is to put all that static HTML into another page and include() it.

1
  • Just learning what "PHP Pros" do, but as far as HTML applications are concerned it seems like using include would be the way to go. Commented Dec 14, 2017 at 18:44
6

Man, PHP is not perl!
PHP can just escape from HTML :) http://www.php.net/manual/en/language.basic-syntax.phpmode.php

if (is_single()) {
//now we just close PHP tag
?>
</style> 
<script> 
<blah blah blah>
<?php
//open it back. here is your PHP again. easy!
}
?>

I wonder why such many people stuck to ugly heredoc.

3
  • 2
    Heredoc isn't that ugly, and is useful if you want to create a string and/or interpolate a lot of variables. Otherwise, the PHP escape is a much cleaner solution. But I think I'm glad Perl can't do that.
    – Duncan
    Commented Apr 20, 2010 at 5:13
  • 1
    Oh I have ... but the Perl code I have been maintaining is enough of a nightmare without it being mixed in with HTML. Especially since HTML would probably compile in Perl :)
    – Duncan
    Commented Apr 20, 2010 at 5:53
  • after converting my application to mvc, i was happy to be able to just close my php block like this and write my javascript like the good 'ol days. =D
    – Kristian
    Commented Jan 3, 2012 at 22:21
5

Your problem is actually caused by:

$('input_6').hint('ex: [email protected]');

You need to escape the single quotes to be \'

However: Using a Heredoc is a much better idea, as it will be much cleaner overall.

5
  • uh oh care to prove about a heeredoc? and what about templates? And what about syntax highlight? Are you fan of editing huge HTML not as HTML but as single colored PHP string? Commented Apr 20, 2010 at 5:07
  • 1
    I prefer templates (Smarty), but in this case that would seem a bit too elaborate for his question. I am a fan of using Heredoc over a massive echo statement. Your solution is also good too, but it doesn't allow me to put variables into the text (easily) I would have to do <?php echo $blah;?> which can get annoying. Commented Apr 20, 2010 at 5:08
  • "which can get annoying" OMG, open your eyes! every current framework uses it for templates, instead of monstrous and useless smarty Commented Apr 20, 2010 at 5:11
  • I like doing {$variable} instead of <?php echo $variable;?> it's just a personal preference... Commented Apr 20, 2010 at 5:13
  • @webdestroya a middle ground, if it's turned on you can use php shorthand and do <?= $variable ?> Commented Apr 20, 2010 at 5:24
4

To expand on @hookedonwinter's answer, here's an alternate (cleaner, in my opinion) syntax:

<?php if (is_single()): ?>
    <p>This will be shown if "is_single()" is true.</p>
<?php else: ?>
    <p>This will be shown otherwise.</p>
<?php endif; ?>
1

Just break out where you need to.

<html>
(html code)
<?php
(php code)
?>
(html code)
</html>

Do not use shortened-form. <? conflicts with XML and is disabled by default on most servers.

0

I prefer to concatenate multiple Strings together. This works either for echo AND for variables. Also some IDEs auto-initialize new lines if you hit enter. This Syntax also generate small output because there are much less whitespaces in the strings.

echo ''
    .'one {'
    .'    color: red;'
    .'}'
    ;

$foo = ''
    .'<h1>' . $bar . '</h1>'  // insert value of bar
    .$bar                     // insert value of bar again
    ."<p>$bar</p>"            // and again
    ."<p>You can also use Double-Quoted \t Strings for single lines. \n To use Escape Sequences.</p>"
    // also you can insert comments in middle, which aren't in the string.
    .'<p>Or to insert Escape Sequences in middle '."\n".' of a string</p>'
    ;

Normally i start with an empty string and then append bit by bit to it:

$foo = '';

$foo .= 'function sayHello()'
    .'    alert( "Hello" );'
    ."}\n";

$foo .= 'function sum( a , b )'
    .'{'
    .'    return a + b ;'
    ."}\n";

(Please stop Posts like "uh. You answer to an five jears old Question." Why not? There are much people searching for an answer. And what's wrong to use five year old ideas? If they don't find "their" solution they would open a new Question. Then the first five answers are only "use the search function before you ask!" So. I give you another solution to solve problems like this.)

1
  • Did you set that indentation in Your IDE (to set multilined string aligned to each part)?
    – Jazi
    Commented Jun 15, 2016 at 11:40
0
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
1
  • echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() -- it should be printf() without echo every time. Commented Apr 16, 2022 at 2:30
-2

You can achieve that by printing your string like:

<?php $string ='here is your string.'; print_r($string); ?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.