Parsing HTML

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
ebolaseph
Forum Newbie
Posts: 1
Joined: Mon Jan 24, 2011 1:19 pm

Parsing HTML

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Parsing HTML

Post 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>
(#10850)
Post Reply