views:

59

answers:

4

Hi,

Seems like a simple question, but I haven't been able to find a solid answer anywhere. I'm outputting a ton of HTML and find escaping "s to be error prone and hard to read, but I also want to have my HTML formatted nicely.

Want something like this (though I know this won't worK):

echo '<div id="test">\n';
echo '\t<div id="test-sub">\n';
echo '\t</div>\n';
echo '</div>\n';

What is one to do?

Thanks.

A: 

use double quotes

or a multi-line echo string:

echo '<div id="test">
    <div id="test-sub">
    </div>
</div>';

or templates.

SilentGhost
why the downvote?
SilentGhost
@SilentGhost: sorry, @SilentGhost, I must have clicked on downvote without realizing... (FF crashed while I was reading this post). I cannot remove the vote now though, if you edit the answer I will surely remove it.
nico
@nico: done, thanks for letting me know.
SilentGhost
ok, great, what's the second downvote for?
SilentGhost
@SilentGhost: No problems
nico
+3  A: 

did you look on HEREDOC

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped

example of advantage here : http://www.shat.net/php/notes/heredoc.php

Haim Evgi
I've tried HEREDOC in the past. Would look into your info but the link isn't working for me.
evanmcd
Try http://php.net/heredoc instead.
Marc B
+2  A: 

There are a lot of ways to make sure, this works just fine for example (PHP_EOL is a cross Platt form Constant for a new line Char (EndOfLine) ):

echo "<div id=\"test\">".PHP_EOL;
echo "\t<div id=\"test-sub\">".PHP_EOL;
echo "\t</div>".PHP_EOL;
echo "</div>".PHP_EOL; 
Hannes
Yeah, PHP_EOL is one option, though I don't know of a comparable constant for a tab, do you?
evanmcd
@evanmcd you can make your own constants... And make your code even harder to read.
Col. Shrapnel
Hannes
A: 

I make use of a small set of classes I wrote in order to output nicely formatted HTML. If you are interested you can find it here.

To get what you want, I would end up writing something like

$mypage = page::blank();
$mypage->opennode('div', 'id="test"');
$mypage->opennode('div', 'id="test-sub"');
$mypage->closenode(2); // div, div
echo $mypage->build_output_strict();

Another alternative would be to use a full-fledged template engine, of which there are quite a few.

Hammerite
Thanks for the answer, that seems even harder to read to me, though.
evanmcd
@ whoever downvoted - I generally feel that if someone downvotes an answer he should leave a message stating his reason for doing so.
Hammerite