Page 1 of 1

Parsing HTML

Posted: Mon May 02, 2011 2:16 pm
by ebolaseph
If this question has been previously answered or addressed, please post me links to material where I can read up on the topic.

I have been working on a web application for the last 6 months and have struggled to decide between two methods of ?parsing? the html from php.
For this topic here are two methods of writing the html that are overly simplified for debate.

Method 1 (live parsing):

Code: Select all

<?php
     echo '
<html>
<head>
</head>
<body>
<div id="username">
';
     if( isset( $_COOKIE['username'] ) ) {
           $username = $_COOKIE['username'];
          echo $username;
     }
     echo '
</div>
</body>
</html>
';
?>
This method inserts the variables into the html code immediately. This could have advantages in that HTML is read top down and this would force the developer to code his php similarly.

Method 2 (delayed parsing):

Code: Select all

<?php
     if( isset( $_COOKIE['username'] ) ) {
           $username = $_COOKIE['username'];
     }
     $HTML .= '
<html>
<head>
</head>
<body>
<div id="username">'. $username .'</div>
</body>
</html>
';

     echo $HTML;
?>
This method allows the functions or php code to run first and populate the page as a string first, then echo the entire $HTML variable and this provide html for the browser to interpret.

Re: Parsing HTML

Posted: Mon May 02, 2011 5:57 pm
by Christopher
Neither way. I would recommend separating your domain/business logic from your presentation/display logic. This example is does not really have any domain/business logic, but hopefully you get the idea. In essence, you want to separate where using PHP as a programming language from where you are using PHP as a template language. Separate files is better -- hence MVC.

Code: Select all

<?php
// domain/business logic
     if( isset( $_COOKIE['username'] ) ) {
           $username = $_COOKIE['username'];
     }

// presentation/display logic below
?>
<html>
<head>
</head>
<body>
<div id="username"><?php echo (isset($username) ? $username : 'No Username'); ?></div>
</body>
</html>