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

<? 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?

+7
html php
source share
12 answers

You can use alternative PHP 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 must be included explicitly, otherwise you will have to write <?php every time.

+23
source share

You can implement the MVC design pattern (Model, View, Controler), your code can be used as a mode for loading the view:

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

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

+5
source share

For the best possible future (constructive) maintainability, I would suggest something like the following:

 <?php if ($id == 2){ $someText = 'I like your id!'; }else{ $someText = 'I love your id!'; } ?> <html> ...complex html... <p><?php echo $someText ?></p> <!-- or <?= $someText ?> --> ...complex html... </html> 
+4
source share

I recommend HEREDOC for some HTML code.

Like this:

 <?php if($id==2) echo <<<EOT Blah EOT; else echo <<<EOT Your id is <b>{$id}</b> EOT; ?> 

Alternatively, you can try an approach in which you have two files: a php file and a phtml file. The php file is the main logic, then the phtml file is the html output.

As in your example,

 // logic.php file if($id==2) $sOutput = 'Yes'; else $sOutput = 'No'; // somewhere at the end of the file include 'logic.phtml'; // logic.phtml <html> <title><?=$sOutput?></title> <body> Blah blah blah <?=$sOutput?> you can login </body> </html> 
+2
source share

Like many others, you can use MVC, or if you do not want to implement a strict MVC structure, you should still use a template system.

This does not mean that you need to learn smarter, you can write your own template system using only the function that you really need.

If you are not working with designers and performance is not the first thing, you can create an html file with simple placeholders where the dynamic content should go, and then replace it with php (str_replace, preg_replace) .. but it will be slower your application.

Example:

 //html template // the @[var] syntax is just as an example <title>@[title]</title> <body> @[content] </body> 

and your template file:

 $title = 'Hello world'; if($id == 2){ $content = get_content(); }else{ $content = get_another_content(); } //really, this is just as example ;) ob_start(); include('template.html'); $output = ob_get_clean(); echo str_replace( array('@[title]', '@[content]'), array($title, $content), $output ); 

This is a really basic example and has 2 problems:

  • Performance
  • Designers should be instructed NOT to touch the placeholders.

A simpler solution could be:

 //html template <title><?php echo $title; ?></title> <body> <?php echo $content; ?> </body> 

and php:

 $title = 'Hello world'; if($id == 2){ $content = get_content(); }else{ $content = get_another_content(); } include('template.php'); 

But echo-html should be reduced as much as possible, it is not good practice and combines logic with content Logic is logic, data is data, and life is good

+2
source share

I like and use soulmerge method. But come out even more:

 <?php if ($id == 2) echo <<< END <h2>some html</h2> END; else echo <<< END <h2>another html chunk</h2> END; ?> 
+1
source share

You can do it like this:

 <? $html_1 = <<<EOH my html goes here EOH; $html_2 = <<<EOH my html <i>something else</i> html goes here EOH; echo ($id==2?$html_1:$html_2); ?> 

Buuut, if you want to facilitate the work of your designers, just use external files:

 <? $html=($id==2 ? file_get_contents("html_1.html") : file_get_contents("html_2.html") ); $html=str_replace("%php generated content%", 1 + 1, $html ); echo $html; ?> 

and use your predefined keywords to insert the calculated php content (in this case,% php generated content% is replaced with 2 (1 + 1) in this example)

0
source share

I personally do not like to use short tags, because I consider them inconsistent between files and prefer to stick to one method. You can instantly make it more understandable with some simple changes:

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

A little easier than some other answers, but also how I found the most readable. This is really about your own preferences, although many other good methods have been suggested (this is exactly how I did it).

0
source share

By adding DaNieL to your answer, you can do something like:

 function htmlVars($html, $vars){ $html = preg_replace_callback('/@\[([0-9a-zA-Z_\$]*)\]/',function ($matches) use ($vars){ return isset($vars[$matches[1]])?$vars[$matches[1]]:""; },$html); return $html; } 

Example:

 echo htmlVars('foo is @[foo] and bar is not @[bar]', Array('foo'=>'foo','bar'=>'barz')); 

Result:

 foo is foo and bar is not barz 

Anonymous functions only work for php 5.3 or higher

0
source share

There really are two cases:

1) Template code. I would recommend the alternative syntax soulmerge approach for control structures.

2) Briefly, PHP code with a helper view that generates output (usually for subsequent substitution) that does not necessarily deserve its own subpattern.

For 2, I prefer something like:

 public function draw(){ $html = array(); foreach($this->item as $item){ $html[] = <<<EOD <li class="{$item->class()}">{$item->label()}</li> EOD; } return implode($html); } 

I prefer this over any alternative that may include ob_start() and ?> <?php blocks. You always want your functions to return strings, rather than directly outputting echoes, so that callers can concatenate and otherwise manipulate the results without transferring the load of buffering the output to the called party.

heredoc makes it easy to identify the output of a line, and although I think the indent break is kind of ugly, it becomes quite effective as your html output stands out as small sticky notes. This, and the fact that in my IDE (PDT), it becomes well-highlighted in green. (Not visible here in SO highlighter ...), so it always clearly indicates in which "mode" I enter.

In contrast, the ?> <?php method makes it difficult to extract html from php code. Once you do this a couple of times, it becomes annoying to keep track of whether you need ?> Or <?php . Finally, it is often more difficult to make replacements with <?php echo $obj->func() ?> Vs {$obj->func()}

If your code becomes more complex, it may be time to reorganize. I like heredoc because if I do something ad-hoc it will stand out and become really obvious a couple of months after the line (ad-hoc tends to degenerate to a ball of dirt as requirements are added) when I got 40 heredoc lines that could start as 5. When I go back and look at my code and develop a not completely ad-hoc version, it is much easier to identify the parts of the file where I was bad. This refers to the green notes I made regarding indentation.

0
source share

Using this is a PHP echo. If this is what you want, that is - it may be more readable to continue what you do if you output a lot of HTML.

-2
source share
  <?php if($id == 2) { //echo all your html stuff echo "<title>Title is where id is 2</title>"; echo "<h1>Hellow</h1>"; } else { echo "<title>Title is where id isn't 2</title>"; } ?> 
-2
source share

All Articles