SitePoint Sponsor

User Tag List

Results 1 to 25 of 29

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Feb 2012
    Location
    Bali
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    HTML output in PHP - looking for a really elegant way

    Hi there,

    I am learning a little bit more about PHP syntax and efficiency. I am actually more a HTML and CSS lover but since I work a lot with Wordpress I have to look deeper into PHP.

    So here I am.
    To the point.

    I would like to know if somebody can tell me if this can be done more efficient respectively with an easier syntax:

    PHP Code:
    $output "\n\t\t".'<tr class="' $funky_zebra '" title="See details for this Event">';
    $output.= "\n\t\t\t".'<td class="ev-date">' $event_start $event_end '</td>';
    $output.= "\n\t\t\t".'<td class="ev-name"><a href="' $event_permalink '">' $event_title '</a></td>';
    $output.= "\n\t\t\t".'<td class="ev-location">' $event_location '</td>';
    $output.= "\n\t\t\t".'<td class="ev-status ev-status-' $event_status_color '">' $event_status '</td>';
    $output.= "\n\t\t".'</tr>';
    echo 
    $output
    I would like to have get code that is indented properly. Ideal would be if I can just use tabstops within the code and without having to write all this \n and \t.

    Any help is appreciated.

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    You can break in/out of PHP as you see fit, for instance...

    Code:
    <div id="user-info">
        <h4><?php echo $user->name; ?></h4>
        <ul>
            <?php foreach($user->orders as $order): ?>
                <li>
                    <a href="#"><?php echo $order->ref; ?></a>
                </li> 
            <?php endforeach; ?>
        </ul>
    </div>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,033
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by AnthonySterling View Post
    You can break in/out of PHP as you see fit, for instance...

    Code:
    <div id="user-info">
        <h4><?php echo $user->name; ?></h4>
        <ul>
            <?php foreach($user->orders as $order): ?>
                <li>
                    <a href="#"><?php echo $order->ref; ?></a>
                </li> 
            <?php endforeach; ?>
        </ul>
    </div>
    Even better...

    Code php:
    <div id="user-info">
        <h4><?= $user->name; ?></h4>
        <ul>
            <?php foreach($user->orders as $order): ?>
                <li>
                    <a href="#"><?= $order->ref; ?></a>
                </li> 
            <?php endforeach; ?>
        </ul>
    </div>

    As of PHP 5.4 <?= will be available at all times. Prior to 5.4 you must have short_open_tags set to on to use it.

  4. #4
    SitePoint Member
    Join Date
    Feb 2012
    Location
    Bali
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Michael,

    I have never seen a syntax like that.

    PHP Code:
    <?= $order->ref?>
    Is it the same like the echo function but shorter?

  5. #5
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,033
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Yes. <?= $string ?> is equivalent to <?php echo $string ?>

    Also, you can capture the output of echo statements using the output buffers.

    Code php:
    <?php
     
    $string = 'Hello World';
     
    ob_start();
    ?>
    I would like to say, "<?=  $string ?>"
     
    <?php
    $output = ob_get_clean();
     
    echo $output; // I would like to say "Hello World"
     
    ?>

  6. #6
    SitePoint Guru
    Join Date
    Nov 2003
    Location
    Huntsville AL
    Posts
    689
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    You could also consider a PHP based templating system such as Twig:
    Code:
    <tr class="{{ funky_zebra }}" title="See details for this Event">
      <td class="ev-date">{{ event_start }} {{ event_end }} </td>
      <td class="ev-name"><a href="{{ event_permalink }}">{{ event_title }}</a></td>
      <td class="ev-location">{{ event_location }}</td>
      <td class="ev-status ev-status-{{ event_status_color }}">{{ event_status }}</td>
    </tr>
    The {{ $var }} is basically the same as <?php echo $var; ?> with the added bonus of doing html escaping automatically. And you can add conditions. looping and custom functions without much trouble.

  7. #7
    SitePoint Member
    Join Date
    Feb 2012
    Location
    Bali
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb

    @ Michael

    That looks totally awesome and is pretty much what I was looking for.
    I will make the code much easier to read.

    Thank you so much!

    @ ahundiak

    Thank you!
    I haven't heared about Twig yet. It is something that would also work in my theme programming for Wordpress?
    Does it make sense to use it in such an environment?

    and

    And you could consider walking across the Interstate in rush hour traffic, but that doesn't mean it's smart or wise to do. Then again, my opinion of (and disdain for) template engines within PHP (which is itself a template engine) is well documented.
    I can imagine that people might think that such kind of thing is not useful or even needless BUT
    I think it is a bit like when some people like to walk barefoot while other people like to use boots.

    Who can tell how they feel and why they do it? And maybe they enjoy it even when it looks to others like the most silly thing in the world.

  8. #8
    SitePoint Member
    Join Date
    Feb 2012
    Location
    Bali
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Anthony,

    that is definitely something that I will try in some parts of my programming as it will makes things easier.
    What I don't like about it is that it becomes a bit messy of I have a lot of if- and else-statements in the code and when I want to place
    some comments for the documenation of my code it might become even hard to read.

    What I like about my version is that I can always add to the variable $output and just echo it in the end of all if-statements or loops.
    I can basically write a little function or just collect all information or code elements that I need and place the echo of my variable where ever I want
    and I know there will be no output of HTML code before.

  9. #9
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,151
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    I wouldn't recommend using Twig with Wordpress since it will add yet another layer of what is really unnecessary complexity. Just stick with breaking in and out of PHP as @Michael Morris and @AnthonySterling have said.

    Off Topic:


    That @ thing doesn't seem to be working or maybe I'm doing it wrong…
    The only code I hate more than my own is everyone else's.

  10. #10
    SitePoint Member
    Join Date
    Feb 2012
    Location
    Bali
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oddz,
    thank you for the information.

    And what do you mean by that?
    "That @ thing doesn't seem to be working or maybe I'm doing it wrong…"

    I always tought that it is very useful and easy to understand as a reference, so to speak.
    I can imagine that it is odd because we are talking about programming, where each symbol has it's own meaning
    and when I use it in my text it looks like I am trying to execute code. ???

  11. #11
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Have to say I never used to like templating engines, but now I use a simple one all the time. Smarty is way too much bloat for me, but it feels so much cleaner now I am using a proper templating syntax and engine. You can separate the logic (of which there is some - foreach, if, for, while, do are all different) from the output, and caching can be utilised effectively as well to speed things up. Just because PHP started out as a templating engine doesn't mean it is the best tool for every single job. The syntax of a template (at least the simple one I use) is far easier to edit and manage than one with <?php, ?> littered everywhere, not to mention the fact that the 'templating syntax' of the control statements everyone seems so keen on clutters things up even more and breaks bracket matching in most editors. Also, escaping, formatting etc can be handled for you by a templating engine in an easy syntax, and since the templates aren't processed as PHP, others working on your files can't break your site / do anything dangerous (accidentally or not) - you can throw your own friendly errors if a template is broken syntactically rather than just have PHP fatal error on you.

    I see nothing but advantages from using a [b]simple[/u] templating engine. Smarty etc goes too far imo - I'm talking about a single class really. The only argument against seems to be people clinging on to the notion that this is how PHP started- well yes, but things have changed a lot since then, and so should the way we develop applications.

  12. #12
    SitePoint Guru
    Join Date
    Nov 2003
    Location
    Huntsville AL
    Posts
    689
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    You can probably already see areas that this can be improved upon and elaborated - this is just sufficient to demonstrate the principle. And this will run faster and cleaner than anything in any template engine out there like Smarty or Twig.
    Didn't mean to start yet another war. Or maybe I did. Slow day at work.

    You really should consider downloading the Symfony2 zip file and pointing your web browser at the sample app directory. Takes almost no effort to get started. Then look at the generated twig files under app/cache/twig. You might be surprised to find out that the generated code is actually just about as clean and as fast as what you posted. Bottom line is that there is no way that you say that performance is an issue.

    Your example is complete unrealistic. How do you know that your title (or any other content) doesn't contain special html characters (such as &) which will mess up then generated html and possible do fun things like put the browser into quirks mode? So you need some kind of system to prevent that sort of thing. In Twig it is automatic. How about in yours?

    Your example also shows a complete page in your .phtml file. Are you seriously suggesting that you don't have some kind of master base page that wraps around individual content pages? Of course you do. So now you have to deal with having a individual content page that fits inside of a master page and is capable of going outside it's own contact block and setting the title. Or maybe some javascript. Or maybe you have a side bar that more or less lives on it's own. Or maybe you have some widgets that you want to scatter about the page. Ultimately you need some what to bring all this together.

    So my challenge to you would be to pick a few of the AcmeDemo pages from the Symfony2 bundle and show how you would do the same using straight php. Then we can compare development time as well as execution time. I'd really be interested in the results.

    If you are not interesting in doing something like this then how about wrapping up a few of your actual deployed to production pages and I'll convert them to Twig. I really think it would be a good experiment. But again, let's make sure it is real.

  13. #13
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,033
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ahundiak View Post
    Didn't mean to start yet another war. Or maybe I did. Slow day at work.

    You really should consider downloading the Symfony2 zip file and pointing your web browser at the sample app directory.
    Not interested in programming in YAML.

    How do you know that your title (or any other content) doesn't contain special html characters (such as &) which will mess up then generated html and possible do fun things like put the browser into quirks mode? So you need some kind of system to prevent that sort of thing. In Twig it is automatic. How about in yours?
    I'm not the designer's babysitter, and neither is my code. The only time such filters make sense is when dealing with end-user supplied content. Using them elsewhere is unnecessary overhead.

    Your example also shows a complete page in your .phtml file. Are you seriously suggesting that you don't have some kind of master base page that wraps around individual content pages?
    What part of rudimentary did you not understand?

    I use a templating system. That means I do use templates. Hell, in my example the class was called "Template" and that should have been a clue that, no, I'm not against using templates. What I'm against is coming up with a new syntax or language specifically for the templates and then parsing that language in PHP. I'd rather use PHP itself to parse the templates.


    If you are not interesting in doing something like this then how about wrapping up a few of your actual deployed to production pages and I'll convert them to Twig. I really think it would be a good experiment. But again, let's make sure it is real.
    Don't even get me started thinking about the living HELL I've had to put up with in production for the last two years. The code is approaching 9 years old, executive meddling has prevented any meaningful revision in that entire time, blocks of the turd are written in PHP 3, there are 5 data modelling systems in place, 3 distinct incomplete frameworks and that's just the surface of 3 pages of critical problems with the thing.... just, no. What I deal with day to day is a sterling example of how not to code.

    The system I've cited is from a new framework I'm working on, but its not complete and I can't find the time and energy to complete it.

  14. #14
    SitePoint Addict FizixRichard's Avatar
    Join Date
    May 2003
    Location
    UK
    Posts
    372
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Michael Morris View Post
    I'm not the designer's babysitter, and neither is my code. The only time such filters make sense is when dealing with end-user supplied content. Using them elsewhere is unnecessary overhead.
    Well personally I would advocate that a programmers code should protect against the actions of anyone other than the developer. Of course this depends on the environment in where the application will be used and who will ultimately be working with the application.

    I've delivered solutions to plenty of clients where there is a marketing department, where some marketing or design person who is versed in HTML will be altering the UI from time to time, outside of a CMS capacity. Should my system allow this individual to do what they need to do, as per the companies requirements, in a safe manner. Or should I tell them that they need to replace their marketing guy with a designer who is versed technically from a programming perspective?

    For example, I had a client a couple of years back who had an internal design and marketing department, one of the staff members was a designer who was "trained as a web designer" and would be adding custom skins to the site at certain seasons (Christmas, Easter, Summer and Autumn if I recall correctly). Their task; as in what they wanted to do each "season" would require them to do some amount of HTML editing on the site.

    The template engine I delivered to them allowed this designer to create separate seasonal skins which were activated and deactivated (preserving the default skin), allowed the designer to create their skin updates without having to concern themselves with PHP code at all; as the PHP code shouldn't affect them, and the system prevented them from inputting any PHP code, accessing any data they shouldn't access or modifying any variables. So if the designer decided they wanted to be smart (ill judgement) or made any silly mistakes it wouldn't affect the operations of their application.

    Of course this all depends on how the system will be used and who will have access to it, your comment above is only really relevant if you know for certain your system is only going to be handled by skilled and experienced developers and designers, which isn't always going to be the case.


    Quote Originally Posted by Michael Morris View Post
    What part of rudimentary did you not understand?

    I use a templating system. That means I do use templates. Hell, in my example the class was called "Template" and that should have been a clue that, no, I'm not against using templates. What I'm against is coming up with a new syntax or language specifically for the templates and then parsing that language in PHP. I'd rather use PHP itself to parse the templates.
    Then quite frankly I'm not sure what this argument is about?

    I for one never advocated using Smarty (I can't stand Smarty and agree it bloats the application) and don't advocate creating a template language that needs to be parsed unless the solution explicitly calls for such a thing to exist.

    The rudimentary template system you demonstrated in your post is achieving exactly what I'm advocating, how templates are structured and the features of the "engine" are of course purely down to developer preferences and project requirements. If a system demands only a simplistic template engine then that's great, if it demands something more feature-some then you can introduce that.

    I don't believe that HTML should be embedded into your applications code, that approach is just messy and can lead to problems down the line, so some kind of template engine, even a rudimentary one like the one you demonstrated, is required in most circumstances.

    I still don't think its a good idea to allow PHP code to be entered directly into templates. In doing so and I feel in your responses, you are making a lot of dangerous assumptions about who will be coming into contact with the application in the future.


    Quote Originally Posted by Michael Morris View Post
    Don't even get me started thinking about the living HELL I've had to put up with in production for the last two years. The code is approaching 9 years old, executive meddling has prevented any meaningful revision in that entire time, blocks of the turd are written in PHP 3, there are 5 data modelling systems in place, 3 distinct incomplete frameworks and that's just the surface of 3 pages of critical problems with the thing.... just, no. What I deal with day to day is a sterling example of how not to code.

    The system I've cited is from a new framework I'm working on, but its not complete and I can't find the time and energy to complete it.

    It is interesting you say this, the two biggest issues I encounter as a developer, when working with existing systems are:

    1. Poor code structure and code bases that have been hacked about by developers in a bad manner; leading to systems that are difficult to maintain and often have issues that have been introduced at some point down the line.

    2. Code bases that don't use template engines, where a "designer who knows some PHP" has attempted to make UI changes or front end redesigns and caused damage to the system in some way because they as a non developer didn't really understand the systems code base or appreciate the nuances of development that is second nature to developers.

    Introducing some kind of template engine, preferably that prevents PHP insertion into templates can help the second problem and in some cases help the first; as oftentimes I have found its UI type changes that are leading to the hacking around of code by a designer who has been hired to do some design work but has also taken on a few bits that involve a bit of coding.
    FIZIX - Full Service Digital Agency - Engaging websites, apps and games.
    Follow us @FIZIXAgency

  15. #15
    SitePoint Guru
    Join Date
    Nov 2003
    Location
    Huntsville AL
    Posts
    689
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    I think I can sympathize. My primary job is maintaining a 3D CAD application first deployed in 1985. Based on C with several propriety object systems on top. So much fun but it pays the bills.

    Very thankful that I can actually design, build and deploy more or less modern PHP web sites as a hobby. You should try it. Here is one being used to organize a big soccer tournament in Knoxville in July: www.zayso.org/natgames

  16. #16
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,033
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Heh heh.. I write plays and do non programming things for a hobby.

  17. #17
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    Single quotes are white-space preserving, so why are you using multiple string additions?

    Code:
    $output='
    		<tr class="'.$funky_zebra.'" title="See details for this Event">
    			<td class="ev-date">'.$event_start.$event_end.'</td>
    			<td class="ev-name"><a href="'.$event_permalink.'">'.$event_title.'</a></td>
    			<td class="ev-location">'.$event_location.'</td>
    			<td class="ev-status ev-status-'.$event_status_color.'">'.$event_status.'</td>
    		</tr>';
    NOT that as a rule I like building strings of markup, since string addition is slower than delimited output. A comma delimited echo is faster to execute and more reliable/predictable.

    Code:
    echo '
    		<tr class="',$funky_zebra,'" title="See details for this Event">
    			<td class="ev-date">',$event_start,$event_end,'</td>
    			<td class="ev-name"><a href="',$event_permalink,'">',$event_title,'</a></td>
    			<td class="ev-location">',$event_location,'</td>
    			<td class="ev-status ev-status-',$event_status_color,'">',$event_status,'</td>
    		</tr>';
    Kind of laughing at the responses so far, many of which advocate throwing MORE code at something so simple... from templating library bloat to the idiotic "let's open and close php on every line" nonsense...

    I'm just wondering why you thought you needed to use double quotes and /t /n just to add carriage returns and tabs...

    Off Topic:

    ...and why you'd put TITLE on a TR, or if those classes are even necessary since you could leverage colgroups for everything but FF and nth-child/sibling selectors for geckotards...

  18. #18
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    You guys are funny, if not a little preoccupied with your own opinions sometimes.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  19. #19
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,033
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Hey! I resemble that remark.

  20. #20
    SitePoint Member
    Join Date
    Feb 2012
    Location
    Bali
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi there,

    I wasn't here for a couple of days.
    Thanks for keeping up answering.

    deathshadow60:
    I will try your recommendation as it seems to be sensible.

    I'm just wondering why you thought you needed to use double quotes and /t /n just to add carriage returns and tabs...
    I am just getting into the potential of PHP and with my example code I tried to create a clean ouput of HTML code.
    I know now that there are better ways to do it and that was my main intention in coming here and ask my question.

    Thank you guys!

  21. #21
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,276
    Mentioned
    18 Post(s)
    Tagged
    0 Thread(s)
    Personally, I like both raw PHP and Twig. For the Symfony fans here, remember that raw PHP is the template system in Symfony 1.

    But I also don't think we should ignore the advantages that can come from an extra layer of templating logic. It can allow our output to be automatically HTML escaped, which I think is the biggest advantage. It keeps our applications secure by default. We'd have to go out of our way to screw up. The second-best advantage is that it prevents UI coders from mucking around. Of course, you could just tell everyone to only write templates in the proper way, but eventually someone -- maybe a new hire -- will be less than perfect. I think it's a good thing when the language helps you enforce good practices. And finally, a new syntax designed for templates, and templates only, can be slightly shorter and easier to type. This last one is clearly the least significant advantage, but it's an advantage nonetheless.

    If it's performance you're worried about, then there's two things to keep in mind. The first is that, if you profiled a real-life application with database fetches and inserts and other logic, I'd wager that a templating engine would be a small factor of the overall performance. And the second thing to keep in mind is that Twig, at least, actually compiles the templates to raw PHP. So it parses the template just once, and every request thereafter is served as raw PHP.


Tags for this Thread

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
  •