php in html?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
dharprog
Forum Contributor
Posts: 126
Joined: Fri Oct 27, 2006 12:20 am

php in html?

Post by dharprog »

Hi

I would like to know is there any way to work out the php code snippets in a html pages?

Means i would like to use php code in html pages will it work? if so how? Please tell me how?

THank You.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

If your webserver allows you to use PHP then you should be able to use the php code snippets. You may have to change your html file extension from .html to .php but the rest should be able to simpy be dropped in. Recommend you simply try it.
User avatar
dharprog
Forum Contributor
Posts: 126
Joined: Fri Oct 27, 2006 12:20 am

Post by dharprog »

Hi

Thanks for the response.

You mean i have to change the html pages to php pages to work out is it?

What i am asking is without changing the extension of .html to .php pages how can i work out the php code in a html page.

Thank You.
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

Set your server up to parse .html files with the PHP engine.

http://php.about.com/b/a/257498.htm
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

To put it very simplistically with an extension of .php (if your webserver recognises it) any php code enclosed in
<?php and ?> tags will be processed. Anything outside of those tags will be simply output as HTML.

Example:

Code: Select all

<?php
  // my "business logic will go here
  $myvar="Well Hello There this is a variable";
?>
<html>
  <head>
  </head>
  <body>
    <p>This HTML will be output</p>
   <?php
       echo "<p>This php echo will also be output</p>";
   ?>
    <p>This HTML will be output</p>
   <?php
       echo "<p>{$myvar}</p>";
   ?>
  </body>
</html>
You may see some examples where only the <? tag is used rather than <?php but this is to be avoided as it relies on certain server settings. Always use <?php.

Normally what you want (ok personal preference) is to try to process as much php as possible at the top of the file and only echo variables within your html. This makes things easier to read. Try to avoid the following:

Code: Select all

<p>This is some starting text</p>
<?php
  if ($somevar == "Eeek") {
?>
     <p>This is shown if variable $somevar is set</p>
<?php
  }
?>
as matching brackets are easily lost.

You may want to start looking at some tutorials on the web to get to grips with this.
Post Reply