如何用HTML编写漂亮的PHP代码? [关闭]

When coding PHP together with HTML, it always seems confusing and very painful to look at. The structure is not easy to understand.

Can anyone tell about how to code PHP with HTML in good structure? php code

There are methodologies out there that help with this issue, such as Model-View-Controller (MVC). MVC seperates your data layer, from your logic, from your presentation (UI) layers. A framework such as CodeIgniter would help you in this case. Even if you weren't going to use an existing framework, seperating out your data models from your business logic and then from your UI objects is relatively easy.

Edit: Let's say you have a shopping cart page. You can have a "view" file called cart.php, and then you can send it information from your other PHP files (the "Controllers"), so that instead of this:

<div id = 'special_price'>
<?php $result = mysql_query("SELECT price FROM pricelists");
 $row = mysql_fetch_assoc($result); 
echo $row["price"]; 
?>
</div>

you can do this:

<div id = 'special_price'><?= $price ?></div>

In this scenario, all logic and data access are handled before you attempt to display the page.

@ajacian81 is right, but there are additional options. The way he mentioned is to write all of your code according to an MVC framework. MVC architecture is an excellent way to separate the concerns of complex web applications. MVC separates application logic, database logic, and views into 3 separate places. However, refactoring an intermixed php+html codebase into an MVC framework can be time-consuming. If you are interested in removing php from your html without entirely refactoring your codebase, consider using a template engine like Twig or Smarty.

If you use a template engine you can separate your php and sql into one location, and your html templates into another location. If you use an MVC framework you must separate your php, sql, and html into 3 different locations. If your priorities are short-term in nature, just use a template engine. If your priorities are long-term in nature, consider refactoring your code into an MVC framework.

Php has gotten so advanced you really won't gain anything using a Framework conviction for custom builds. If you comment out your scripts and every beginning and ending of every section of html and php you will be amazed how fast and how many less files it takes to run a full social website or social business portal. I only use three major files-- config.php, ini.php which stores all my sessions and cookies, and db_connect.php. All my page views are handled by Ajax without page refresh and all my forms are brought into some of these views to using Ajax without page refresh. I have pretty much used Ajax for all my URL request which elliminates the need for bulky frameworks.