alternative way of assigning html in php – php tips

Posted by mahmud ahsan on April 4, 2009 in PHP | 1 Comment

php

পিএইচপি ভ্যারিয়বলে এইচটিএমএল অ্যাসাইন করার বিকল্প রাস্তা
As a facebook application developer, sometimes we need to assign large portion of html,css code in php variable and need to pass that variable in some api. most of the time i found many programmers use this way:

 <?php     $a    =   <<<EOD
<div>         my name is $name         blah blah blah....</div>
EOD;     call_api($a); ?> 


if this type code is small, then its ok i think. but this type of code is not very readable for debugging. because most of the IDE just show this large code one color as a value of php variable. but think… when a large html code is pushed like this way, then its very time consuming for other programmers specially html/xhtml designer to understand. because modern IDE shows html/css tags in different colors, so this makes code very readable and easy to understand.

here i’ve shown an alternative way to solve this problem.

 <?php     ob_start();     include_once "html_markup.php";     $variable  = ob_get_contents();     ob_clean();     call_api($variable); ?> 

html_markup.php should contain html code as it is. like

<div>     My name is <?=$name?>     blah blah blah ......
<div> 

when you call ob_start(), this function will turn output buffering on. while output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

when you call ob_get_contents(), it returns a string of the contents of the output buffer without clearing it.
so you ‘ll get the buffered contents as a string and assign that in a variable.
now you could use this variable for your specific purpose. and if you use this way then after assigning buffered content to variable just call ob_clean(), that will clean (erase) the output buffer.

Random Posts

If you think this article kicked ass, subscribe to the RSS feed or follow me on Twitter! Share with your friends, or leave a comment below (or better still, do both!)

Comments (1)

 

  1. ranacse05 says:

    Nice post :D , thanks

Leave a Reply