Solved

What is the best way to output html and php variables using php?

Posted on 2008-10-30
7
1,043 Views
Last Modified: 2010-04-21
My question is based on opinion on what is the best and easiest way to output html that is mixed with php variables within a php script. As a beginning programmer I was always told to use  something like this:

<?PHP echo '<p>My name is '.$name.'! And I live in '.$place.'.</p>';?>

This way doesn't seem to be the best or easiest way to get an html output page and this way is also hard to debug. What other ways are available that are easier and considered the more accurate way to output html? I have seen some functions but don't know what ones are right for me. Any guidance would be well appreciated.
0
Comment
Question by:NEComputer
  • 4
  • 2
7 Comments
 
LVL 18

Expert Comment

by:Hube02
ID: 22847101
As you say, this is opinion, and opinions are like... well...

anyway, I like the following myself, assuming we are in php

// php code here
?>
  <p>My name is <?php echo $name; ?>! And I live in <?php echo $place; ?>.</p>
<?php
// more php code here


There are a few reasons I like this, most of which is due to the fact that I use DreamWeaver as my coding environment. This allows me to see what is what, and makes finding errors in both php and html easier due to color coding. Many other editors are the same.

Another is that I simply like to keep HTML as HTML and not clutter up my php code with a lot of echo statements to output HTML. The only time I will generally place HTML into strings is if I am building something that needs to be echoed later, or if I am using a function to build a string that is returned. As a quick example, when validating a form I might have a variable named $form_error_messages and I might place all the error messages into this string and then echo them out all with

echo $form_error_messages.

but again, this is only my opinion and what I consider to be good coding practices.

0
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 300 total points
ID: 22847317
There are many options. I would have written your example code like one of the below snippets.
# My preferred way to write this:
echo "<p>My name is $name! And I live in $place.</p>";
 
# When arrays and/or objects are involved:
echo "<p>My name is {$person->name}! And I live in {$address[city]}.</p>";
 
# It also works with apostrophes surrounding the array key: 
echo "<p>My name is {$person->name}! And I live in {$address['city']}.</p>";
# The apostrophes are required when associative arrays are used outside of
# double quotes, so it might be a good idea to allways use it. Easier to remember.
 
# Long lines with much html I often write like this:
echo "<p>".
       "My name is ".$person->name."! ".
       "And I live in ".$address['city'].".".
     "</p>";
 
# ...but it is clearer to write it like this:
echo "<p>".
       "My name is {$person->name}! ".
       "And I live in {$address[city]}.".
     "</p>";
 
# It is also valid to break long lines without using concatination:
echo "<p>My name is {$person->name}! 
     And I live in {$address[city]}.</p>";
# This leaves some extra whitespace between "!" and "And", 
# but in html this is collapsed to a single space on screen.

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22848569
The reason for my coding style (above) for long lines with much html is clearer when there actually is much html... I also switch between using ' and " depending on the content and context of the strings. Html attributes must be within double quotes, javascript string literals must be within single quotes.  I have expanded your example to illustrate:
echo '<div class="presentation">'.
       '<p>'.
         'My name is <a href="mailto:'.$person->email.'" onmouseover="'.
            "Tooltip('Click to send me an email!')".
            '">'.htmlentities($person->name).'</a>! '.
         'And I live in <a href="http://maps.google.com/maps?q='.
           urlencode($address['city']).','.
           urlencode($address['country']).
           '" onmouseover="'.
             "Tooltip('Click to find {$address['city']} on google maps!')".
           '">'.htmlentities($address['city']).'</a>.'.
       '</p>'.
     '</div>';

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22848658
In larger projects with many involved coders and web designers, it is best to NOT mix html and code. Then the code might look like something like below, the template contains "<p>My name is $name! And I live in $place.</p>".
echo ResolveTemplate(
  GetTemplate('PersonalPresentation'),
  array(
    'name' => htmlentities($person->name),
    'place' => htmlentities($address['city'])
    )
  );

Open in new window

0
 
LVL 1

Author Comment

by:NEComputer
ID: 22853521
cxr could you close the quotes and solve the problem when you mention html attributes must use double quotes? Wouldn't it look something like this:
echo "<p>My name is {$person->name}! And I live in {$address['city']}. "\This is my quote."\</p>";

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22853596
Yes, you can escape the double quotes within the double quotes... but I think it is harder to read and easy to get wrong...  you must have the backslash first, like this \", not "\

Like this:
echo "<p>My name is {$person->name}! And I live in {$address['city']}. \"This is my quote.\"</p>";

Open in new window

0
 
LVL 1

Author Closing Comment

by:NEComputer
ID: 31511923
Thanks you for your opinion. Your assistance is greatly appreciated.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How do I remove all except the numbers?  PHP  Regex 3 29
selecting both the price and sum(price ) with mysql statement 5 45
hosting images 4 28
PHP and google maps 13 44
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question