48

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: myname@example.com');
});
</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)?

Thomas
  • 5,030
  • 20
  • 67
  • 100

11 Answers11

143

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;
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 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. – thomasrutter Apr 20 '10 at 05: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 Apr 20 '10 at 07:34
  • points to note: if you use Eclipse (with PDT) to develop PHP, you will find that heredoc has incorrect code highlighting. – Raptor Sep 03 '12 at 03: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 Jul 15 '13 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 Sep 23 '15 at 07:00
73

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.

hookedonwinter
  • 12,436
  • 19
  • 61
  • 74
  • 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 Jun 11 '14 at 19:58
  • 6
    But it is a possible solution, so why -1? – Black Sep 23 '15 at 06:52
  • Just because it's a possible solution, doesn't mean it's a recommended one. @EdwardBlack – Harry Kitchener Jan 19 '17 at 13:26
  • 6
    A solution is a solution. – Black Jan 20 '17 at 16:03
  • 4
    I feel many here, all too many, are a little trigger-happy when it comes to the downvote button. – Matt Cremeens Oct 22 '17 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 Mar 26 '18 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;
jacobianism
  • 226
  • 1
  • 3
  • 12
Galen
  • 29,976
  • 9
  • 71
  • 89
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: myname@example.com');

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: myname@example.com');
});
</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.

thomasrutter
  • 114,488
  • 30
  • 148
  • 167
  • 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. – Rick Henderson Dec 14 '17 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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 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 Apr 20 '10 at 05: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 Apr 20 '10 at 05: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 Jan 03 '12 at 22:21
5

Your problem is actually caused by:

$('input_6').hint('ex: myname@example.com');

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.

Mitch Dempsey
  • 38,725
  • 6
  • 68
  • 74
  • 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? – Your Common Sense Apr 20 '10 at 05: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 `` which can get annoying. – Mitch Dempsey Apr 20 '10 at 05:08
  • "which can get annoying" OMG, open your eyes! every current framework uses it for templates, instead of monstrous and useless smarty – Your Common Sense Apr 20 '10 at 05:11
  • I like doing `{$variable}` instead of `` it's just a personal preference... – Mitch Dempsey Apr 20 '10 at 05:13
  • @webdestroya a middle ground, if it's turned on you can use php shorthand and do = $variable ?> – hookedonwinter Apr 20 '10 at 05:24
3

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; ?>
moteutsch
  • 3,741
  • 3
  • 29
  • 35
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.

user186658
  • 11
  • 3
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.)

hiddenAlpha
  • 390
  • 4
  • 10
  • Did you set that indentation in Your IDE (to set multilined string aligned to each part)? – Jazi Jun 15 '16 at 11:40
0
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
蔡正海
  • 483
  • 4
  • 11
  • `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. – mickmackusa Apr 16 '22 at 02:30
-2

You can achieve that by printing your string like:

<?php $string ='here is your string.'; print_r($string); ?>
Shams Reza
  • 1,087
  • 8
  • 10