Forum Moderators: coopster
Yesterday, I spend some time reading the PHP Bag of Tricks... Now I am a bit confused about the way I used PHP.
1/ First of all, regarding the single and double quotes, I currently use this: echo "<div class='test'>";
that is double quotes for PHP and single quote for HTML (well, browsers are doing the job of changing single to double quotes). I know this is wrong, it should the other way. But what about the speed?
2/ All my HTML is echo using PHP. I know that my PHP should be independent from HTML. But what if, like me, your script has many switch and if statement which output different HTML? Am I the only one to use 100% PHP?
3/ Lastly, I like to assess the speed of my PHP. Nonetheless because my HTML and PHP are "mixed" together, looping 200 times my page would kill my browser and CPU!
Is there a way to loop without rendering 200 HTML pages?
Thanks
echo "<div class='$myvar'>";If you have no variables, you should use single quote as it does not try to look for variables:
echo '<div class="test">';When I use variables in the string, I seperate the string myself.. I'm not sure which is faster, but it allows me to keep double quotes in the html without using backslashes. Like this:
echo '<div class="'.$myvar.'">';You can use double quotes inside the html, but you would need to backslash them.
echo "<div class=\"$myvar\">";
In reply to 2:
Echoing everything is not bad, but if you have a large chunk of html that you want to select because of a switch or function you can use this syntax to avoid having to deal with quote problems.:
print <<<EOF
<div class="test">
Your HTML code is here
</div>
<div class="test">
<img src="test.gif" alt="" />
etc...
</div>
EOF;
echo "<div class=\"test\">";
I don't know if it's the fastest but I have gotten used to it.
2. Smarty is a very powerful template engine that you can use that helps separate HTML and PHP. It also allows you to do switch statements etc. Check it out at [smarty.php.net...]
3. You could use output buffering to clear the buffer after each page iteration. Just an idea.
I know this is wrong, it should the other way. But what about the speed?
If you quote a string in single-quotes, PHP does not need to parse the string checking for variables, ergo using single quotes is faster.
Am I the only one to use 100% PHP?
By no means at all. I have only ever used 100% PHP, and i'm sure there are many, many others who write "pure" PHP as well.
PHP/HTML soup is just plain ugly.
my favourite ;)
check this thread out
Benchmarking PHP text output [webmasterworld.com]
Accumulating all output to a variable and then echoing once is way faster. [...]
Therefore, you never lost much time by echoing, but you can by stepping in and out of PHP.
Happy to hear that I learned the correct way. However, I 'll have to start using single quotes in PHP...