SitePoint Sponsor

User Tag List

Results 1 to 19 of 19
  1. #1
    SitePoint Zealot GHicks's Avatar
    Join Date
    Oct 2003
    Location
    Prescott Valley, Arizona, United States
    Posts
    135
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Dropping in and out of PHP for HTML code or ECHO/PRINT?

    What is the preferred method for writing code? Is it considered best to stay in PHP and use ECHO to output HTML code where needed? Or is it better to drop out of PHP and just code straight HTML code?

    For example, when processing a WHILE loop, maybe you want to make a table out of the results and so need to place your table cell end and start code. Which is the recommended method? Drop in and out of PHP or ECHO?

    I understand the keeping the code separate, I am referring to the times when you NEED to embed them together or assemble a string.

    Thanks!

    Greg

  2. #2
    SitePoint Zealot Sogo7's Avatar
    Join Date
    May 2011
    Posts
    129
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    If you're running through a loop you can't drop in and out from PHP to HTML and back again.

    Instead you bolt all the HTML together for your table inside PHP as a string, then echo it
    all out at once.

    Notice the .= this appends (joins) the string together into one long one.

    PHP Code:
    <?php
    foreach (array('one''two''three''four') as $output) {
        
    $dump_to_screen .= $output." - ";
    }
    ?>


    <!DOCTYPE>
    <head></head>
    <body>
    <?php echo  $dump_to_screen;?>
    </body>
    </html>
    Lovelogic.net Personal Projects Pit - Spammers welcome

  3. #3
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,791
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)
    If you're running through a loop you can't drop in and out from PHP to HTML and back again.
    Technically that's not true...
    Code:
    <ul><?php
    $a=0;
    foreach (array('one', 'two', 'three', 'four') as $output) {
        $a=$a+1;?>
        <li>
        <? echo $a. '] ',$output,'<br>';?>
        </li>
    <? } ?> </ul>
    works.. but it's just ugly and confusing code.

    I don't actually know if there is noticeble a performance hit for dropping in and out of PHP. But I think what ever it is can easily be worth the weight of readable code or easily modifiable templates.

    If other words, what I did above is possible, but not recommended ( more for readability's sake than performance) On the other hand...

    <title><? PageTitle()?</title>

    Or even Long applications of heredoc are not a bad thing. Also, dropping out of PHP makes it easier to preserve your formatting and indenting. I find it quite valuable when debugging my output (HTML) .

  4. #4
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,805
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Output:
    I "prefer" to be able to:

    glance
    understand
    easily edit the script

    value: 0
    value: 1
    value: 2
    value: 3
    value: 4
    value: 5
    footer goes here
    Source:
    PHP Code:

    <table summary='#'  style='text-align:left'>
      <thead>
        <tr>
          <th>
            I   "prefer" to be able to:  
            <ul>
              <li>glance</li>
              <li>understand</li> 
              <li> easily edit the script</li>
            </ul>    
          </th>     
        </tr>    
      </thead>
      
      <?php for($i2=0$i2<=5$i2++) { ?>
        <tr>
          <td>
            <?php echo 'value: '.$i2;?>
          </td>
        </tr>    
      <?php ?>

      <tfoot>
         <tr>
           <td>footer goes here</td>
         </tr>
       </tfoot>  

    </table>

  5. #5
    SitePoint Zealot GHicks's Avatar
    Join Date
    Oct 2003
    Location
    Prescott Valley, Arizona, United States
    Posts
    135
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    dresden_phoenix:

    So would you rather have: (please disregard any coding/typos, think this gets the point across)
    <?php
    echo "<ul>";
    $a=0;
    foreach (array('one', 'two', 'three', 'four') as $output) {
    $a=$a+1;
    echo "<li>";
    echo $a. '] ',$output,'<br>';
    echo "</li>";
    }
    echo "</ul>";
    ?>

    Personally I like John_Betong's style of code myself. It's similar to dresden_phoenix original code, but for whatever reason seems a bit cleaner. I realize depending on what you are action you are actually performing sometimes it could be quite ugly. However, (especially if you are using an editor with code highlighting) I think the potential to have that point out a coding error is more likely.

    Greg

  6. #6
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,246
    Mentioned
    16 Post(s)
    Tagged
    0 Thread(s)
    Based on all the major frameworks, the preferred method is the alternative syntax. It's very similar to John_Betong's code. Here's how it would look:

    PHP Code:
    <table summary='#'  style='text-align:left'> 
      <thead> 
        <tr> 
          <th> 
            I   "prefer" to be able to:   
            <ul> 
              <li>glance</li> 
              <li>understand</li>  
              <li> easily edit the script</li> 
            </ul>     
          </th>      
        </tr>     
      </thead> 
       
      <?php for ($i 0$i <= 5$i++): ?> 
        <tr> 
          <td> 
            value: <?php echo $i ?> 
          </td> 
        </tr>     
      <?php endfor ?> 

      <tfoot> 
         <tr> 
           <td>footer goes here</td> 
         </tr> 
       </tfoot>   

    </table>
    "First make it work. Then make it better."

  7. #7
    SitePoint Zealot GHicks's Avatar
    Join Date
    Oct 2003
    Location
    Prescott Valley, Arizona, United States
    Posts
    135
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm, alternative syntax is an interesting adjustment, but the biggest change I see between the two styles is you change the opening { to : and the closing } to endwhatever. More verbose, but arguably easier to code trace. Seeing what a particular closing } is for is much easier using the alternative syntax method, at the expense of slightly expanded file sizes (albeit the change is negligible). I'll keep that method in mind and try both and I guess just see what I settle into.

    Thank you for the feedback!

    Greg

  8. #8
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,791
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)
    GH,
    Basically I was saying what Jeff just said.. tho I skipped the alternative format. Shame on me! I got lost in trying to say that you CAN HTML withn a PHP loop, you just need to take care to keep your code readable. Gains in readability far outweigh ALMOST any speed gain of dropping in and out of PHP. So I FAVOUR dropping in and out for the reason John listed AND the additional reason that dropping out of PHP preserves your HTML formatting easily ( indents, new lines etc) ...

    I really should have written this as well to keep my example consistent.


    Code:
    <ul>
      <?php for($i2=1,$th=array('st','nd,'rd','th'); $i2<=15; $i2++) : ?>
            <li>I am the<?php echo $i2, (($i2)<3)? $th[$i2-1]:$th[3] );?> list item<li>
      <?php endfor ?>  
    </ul>
    I just added two asides tho.


    1) Use common sense, For small scripts or simple templates it makes little difference. I want to keep my samples sort so the scripts/ mock templates are short and basic. It may not always be the smart thing to do.

    This is NOT clever at all:

    Code:
    <div class="article">
      <?php while($hasNextP()) : ?>
            <p>$getNextP();</p>
      <?php endwhile ?>  
    </div>
    2) you gain a small speed boost using singe quote for non parsed text, also you can eco with "," instead of "." : eg.: echo 'I am static text ',$bar, 'I was joined with a comma instead of a dot because its faster than concatonating with a period'," variable $a and newlines need tobe parsed \n";

  9. #9
    SitePoint Addict kduv's Avatar
    Join Date
    May 2012
    Location
    Maui, HI
    Posts
    211
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    Some may also argue that multiple echo statements would negate the performance gains from avoiding dropping in/out of PHP.

  10. #10
    ♪♪ ♪ ♪ ♪ ♪♪ ♪ ♪♪ Markdidj's Avatar
    Join Date
    Sep 2002
    Location
    Bournemouth, South UK
    Posts
    1,551
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I can gain over 100%, double the execution speed by not using HTML. Great to have further speed tips from dresden_phoenix as well though.

    Take a look at this page to see how I benefit from not using it.

    Basically I only output the very first page with HTML. All subsiquent pages get outputed using JavaScript unless the request is sent by POST. This way I can avoid loading the HTML for the common content for every page load
    LiveScript: Putting the "Live" Back into JavaScript
    if live output_as_javascript else output_as_html end if

  11. #11
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    69 Post(s)
    Tagged
    0 Thread(s)
    ...as long as every person who uses your site enables javascript. Otherwise they're screwed.
    Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.

  12. #12
    ♪♪ ♪ ♪ ♪ ♪♪ ♪ ♪♪ Markdidj's Avatar
    Join Date
    Sep 2002
    Location
    Bournemouth, South UK
    Posts
    1,551
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Is that directed at me StarLion? I think you might want to read a bit more in to it. Or Compare my site with javascript on/off. Works exactly the same way, apart from server, network and client do more work without javascript.

    Have a look in IE with network capturing turned on. It might help see what's happening.

    Oh, and the clock will show the server time rather than local.
    LiveScript: Putting the "Live" Back into JavaScript
    if live output_as_javascript else output_as_html end if

  13. #13
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,246
    Mentioned
    16 Post(s)
    Tagged
    0 Thread(s)
    Sorry to be critical, Markdidj, but my views on this are: 1) It looks like run-of-the-mill ajax. This isn't exactly a breakthrough idea. 2) Even though ajax may yield performance improvements, it's unrelated to the topic of this thread. And 3) I agree with logic_earth from the other thread. The code seems awfully messy and hard to understand.
    "First make it work. Then make it better."

  14. #14
    ♪♪ ♪ ♪ ♪ ♪♪ ♪ ♪♪ Markdidj's Avatar
    Join Date
    Sep 2002
    Location
    Bournemouth, South UK
    Posts
    1,551
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    1) It predates Ajax
    2) It predates Ajax
    3) Why I don't step in and out of HTML
    4) Whitespace was stripped.

    I don't find it messy at all. I find it easier to read when I'm not stepping in and out of HTML. And at over 100% server execution and bandwidth capacity improvements even if it were messy it's worth the bonus!
    LiveScript: Putting the "Live" Back into JavaScript
    if live output_as_javascript else output_as_html end if

  15. #15
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,058
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Markdidj View Post
    I don't find it messy at all. I find it easier to read when I'm not stepping in and out of HTML. And at over 100% server execution and bandwidth capacity improvements even if it were messy it's worth the bonus!
    I think the biggest take-away is

    Quote Originally Posted by Jeff Mott View Post
    it's unrelated to the topic of this thread
    The OP was looking for was a way to separate their HTML from the PHP code, or at least good practices. The problem is your implementation still groups the two together for the content portion, albeit the header and footer may be separate, the content remains a mixture of PHP and HTML output (or at least could).

    @GHicks,

    There are a variety of ways you can go about this, many listed above, others a bit more complicated (in fact, I've been toying with an idea on my latest project, but it isn't anywhere near ready to be shown outside of my test environment and still needs some major refactoring). Personally I like MVC approaches, where separating the content/design from the code is very well indicated.

    Where I believe you are coming from, is what if the content needs to loop through a data structure, how do I make that clean? That is a process I am working through right now, you can kind of consider it as a sub-view to a view. So the view being your cart for example, header, buttons, etc, the sub-view being an individual item that is listed in the cart, and the cart view just calls the sub-view to provide its' output (this is just a very high level overview of the idea, but hopefully shows the process).

  16. #16
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Markdidj View Post
    Is that directed at me StarLion? I think you might want to read a bit more in to it. Or Compare my site with javascript on/off. Works exactly the same way, apart from server, network and client do more work without javascript.

    Have a look in IE with network capturing turned on. It might help see what's happening.

    Oh, and the clock will show the server time rather than local.
    Bet it's a nightmare to debug and work with though.

    I'd be ripping my hair out if I inherited a code base like that.

  17. #17
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Markdidj View Post
    I can gain over 100%, double the execution speed by not using HTML. Great to have further speed tips from dresden_phoenix as well though.

    Take a look at this page to see how I benefit from not using it.

    Basically I only output the very first page with HTML. All subsiquent pages get outputed using JavaScript unless the request is sent by POST. This way I can avoid loading the HTML for the common content for every page load
    But you know you could just cache the common html quite easily?

    Also, upon re-reading your comment here, it appears to just be ajax? Not sure how you're measuring the 100% speed increase either. Not unless you had a massive amount of html to load outside of the content you're swapping via javascript/ajax. Even then, as I say, you could do this without the pain by simply caching those common html elements.

  18. #18
    ♪♪ ♪ ♪ ♪ ♪♪ ♪ ♪♪ Markdidj's Avatar
    Join Date
    Sep 2002
    Location
    Bournemouth, South UK
    Posts
    1,551
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Well, I'm not here for defensive arguments. If you can't see the benefits I'm not here to drill it in.

    I'll step out from here.
    LiveScript: Putting the "Live" Back into JavaScript
    if live output_as_javascript else output_as_html end if

  19. #19
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Markdidj View Post
    Well, I'm not here for defensive arguments. If you can't see the benefits I'm not here to drill it in.

    I'll step out from here.
    Not being funny, but if the code is messy and inflexible then the speed benefit starts to matter less and less. Also, the kind of speed benefits you are likely talking about are probably measured in milliseconds, in which case, unless you're facebook, the supposed benefits are outweighed by the negativity of difficult to maintain code. Just my three penneth.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •