Click to See Complete Forum and Search --> : Formatting code that's been stored in a variable so that it looks pretty in source


CWCJimmy
02-07-2006, 05:28 PM
So, I use PHP variables to store most of my code and just echo those variables when they're needed. I've found that if I write the entire section of code in a single line, then I can control the spacing/tabbing by using '\n' and '\t'. However, that makes it very hard to edit and I prefer to have things broken up in multiple lines with a single variable declaration.

I realize this doesn't matter a whole lot, but sometimes I have to check the parsed code to find a problem and it's rather difficult.

Here's an example:

Desired layout in source:

Row 1
Cell 1
Row 2
Cell 2



//This works
$example1 = "\nRow 1 \n\t Cell \n Row2 \n\t Cell 2";

//This does not work
$example2 = "
Row 1
Cell 1
Row 2
Cell 2";


In $example2 it seems as though the number of tabs before where $example2 is declared is where the code will start in the source. If I add '\n' to any line there will be an extra blank line in the source.

Any thoughts? Did this even make any sense? Am I doing something stupid?

NogDog
02-07-2006, 06:43 PM
$text =<<<EOD
Row 1
Cell 1
Row 2
Cell 2
EOD;

CWCJimmy
02-08-2006, 08:45 AM
Thanks for the reply!

What exactly does this do? I tried it and got a

Parse error: syntax error, unexpected T_VARIABLE



Thanks!

NogDog
02-08-2006, 09:18 AM
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Note the important restriction on the closing heredoc string ("EOD" in my example) which must be the only thing on its line (along with the closing semi-colon) and with no white space before it.

CWCJimmy
02-08-2006, 09:26 AM
Man knowing this earlier would have made my life a lot easier! Haha. I've been using double quotes and hav been escaping every time I needed double quotes inside.

Ahh but unfortunately it seems to affect the source the same way as using single or double quotes. And notepad++ doesn't seem to recognize it =/