Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write php+html in one file more beautiful?

Tags:

html

php

<?
if($id == 2) {
?>
       html goes here
<?
} 
else { 
?>
       if id is not 2 then something goes here
<?
}
?>

How can I write php+html in one file more beautiful without learning smarty?

like image 549
good_evening Avatar asked May 08 '10 22:05

good_evening


People also ask

How do we combine HTML and PHP code?

Mixing HTML and PHP. PHP code is normally mixed with HTML tags. PHP is an embedded language, meaning that you can jump between raw HTML code and PHP without sacrificing readability. In order to embed PHP code with HTML, the PHP must be set apart using PHP start and end tags.

Can I write PHP code in HTML file?

Note: To use PHP in HTML, you have to use the . php extension because In PHP the code is interpreted and run on the server-side. Example 1: PHP.

Where do I put PHP script in HTML?

A PHP script can be placed anywhere in the document. The default file extension for PHP files is " .php ". A PHP file normally contains HTML tags, and some PHP scripting code.

Will a PHP script work if it is in a file with a .HTML file extension?

You can't, unless you instruct Apache to treat . html files as PHP.


2 Answers

You can use PHP's alternative syntax for control structures:

<? if ($id == 2): ?>
    <h2>some html</h2>
<? else: ?>
    <h2>another html chunk</h2>
<? endif ?>

Note that short_open_tags is a php.ini directive that needs to be enabled explicitly, otherwise you would have to write <?php each time.

like image 54
soulmerge Avatar answered Sep 22 '22 06:09

soulmerge


You can implement the MVC (Model, View, Controler) design pattern, your code can be used as a modele to load the view:

<?php
if($id == 2) 
{
 //somes variable and array controls
}
else  
{
 //somes variable and array controls
}
//include the view
include('view.php');
?>

In the view.php, you show the html page with only the echos for php variables and array.

like image 30
Amirouche Douda Avatar answered Sep 23 '22 06:09

Amirouche Douda