How do you indent your HTML? [duplicate] - php

This question already has answers here:
How to properly indent PHP/HTML mixed code? [closed]
(6 answers)
Closed 9 years ago.
Given the HTML generated by my application.
function pagination(){
echo "<ul>\n";
for($i = 1; $i <= 10; $i++)
echo "\t<li>...</li>\n";
echo "</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>
If I add another container DIV, this doesn't produce correctly indented code.
Is there any solution for the function to somehow know how many \t 's or spaces to add, or somehow automatically indent the html?

Amazing question.
9 answers and 3 comments so far, and looks like nobody bothered to read the question body, but just repeated some gospel triggered by a keyword in the title - a most preferred manner to answer questions on the blessed site of stackoverflow.
Yet the question not that simple/one-layered.
I have to admit, it's ambiguous itself. So, we have to dig it out.
1) How do you indent your HTML?
Use templates, dude. Use templates. The only answer.
2) Is there any solution for the function to somehow know how many \t 's or spaces to add, or somehow automatically indent the html?
Of course there isn't.
PHP knows nothing of HTML, indents and such.
Especially when no HTML is ready yet(!)
3) If I add another container DIV, this doesn't produce correctly indented code.
The key question of the question.
The question for sake of which the question were asked.
Yet hardest of them all.
And the answer is kind of ones I showed total disagreement with, hehe:
Although relative order of tags is important, for the resulting large HTML it is possible to move some blocks out of row:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div>
<!-- news list -->
<div>
<ul>
<li>1..</li>
<li>2..</li>
<li>3..</li>
<li>4..</li>
</ul>
</div>
<!-- /news list -->
</div>
<div>
<!-- pagination -->
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
<li>Black</li>
</ul>
<!-- /pagination -->
</div>
</body>
</html>
It will let you have proper indention in the meaningful blocks, yet keep the main HTML in order.
As a side effect it will keep your lines on the screen :)
To keep good indentation inside sub-templates, I'd strongly suggest using PHP-based templates. Not ugly HEREDOC for goodness' sake!
Here is only one rule to follow with PHP templates:
always keep PHP blocks to the left side. That's all.
To keep indentation between PHP nested blocks, just indent them inside <? ?>
Example:
<ul>
<? foreach ($thelist as $color): ?>
<li>
<? if ($color == $current): ?>
<b><?=$color?></b>
<? else ?>
<?=$color?>
<? endif ?>
</li>
<? endforeach ?>
</ul>
This will produce correctly indented HTML, while keeping order of both HTML and PHP in the template, making developer's life easer both at development and debugging.
Do not listen to anyone who says "no need to indent your code at all!". They are merely hobbyists, not the real developers. Anyone who have an idea of what debugging is, who had hard times debugging their code, would tell you that proper indentation is essential.

The answer could sound weird, but you should not worry about the generated code's indentation. Indentation is for readability, and should be only of concern on the programmer's side, not on the generated part (which is for browsers).

I agree with all comments saying don't bother but if you do have a case where doing so makes sense then you can pipe your HTML through HTML Tidy (or in your case PHP Tidy) using the indent option.

Most editors have some sort of formatting function which can be used to fix indentation. In Visual Studio for example you can hit Ctrl + K + D to nicely format your html.

I usually do it something like this if it's a more complicated html structure. This makes it easier to follow if you ask me, and you also can write your html normally instead of worrying about escaping quotes and things like that.
Since you're not in a PHP block when it's processing the HTML, it will come out as indented as you make it.
<?php
function pagination(){
echo "</ul>\n";
for($i = 1; $i <= 10; $i++)
{
?>
<li>...</li>
<?php
}
echo "</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>

You could use heredoc syntax
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
Notice all of the indenting is preserved.
EOT;
?>

If you add \t in front of ul you should be able to see the code prettied up
<?php
function pagination(){
echo "\t<ul>\n";
for($i = 1; $i <= 10; $i++)
echo "\t\t<li>...</li>\n";
echo "\t</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>

I am a stickler for well formed code as well. Alot of people here said "firebug will indent your code for you". Well, what about when the markup delivered to the browser is modified through or injected into the DOM via javascript? Then firebug shows you the current state, not what you loaded from the server.
I also like my html to be visible and readable throughout my script. I generally do something like this, keeping track of PHP and HTML indentation separately (it is not to be able to put your cursor on an opening tag or { and just scroll the page down until you find the closing tag or } conveniently lined up with your cursors position.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div><?php
$thelist = array('Red', 'Green', 'Blue', 'Black');
echo '
<ul>';
foreach ($thelist as $color) {
echo '
<li>' . $color . '</li>';
}
echo '
</ul>';
?>
</div>
</body>
</html>
This outputs just like so,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div>
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
<li>Black</li>
</ul>
</div>
</body>
</html>
Notice is looks just like it should, and like it does in the script (this makes debugging simple for me). I use single quotes with HTML so I do not have to escape a trillion quotes (this makes concatenating strings a bit more manual but it is less work than all those back slashes; which also hinder readability within the script).
Once again, this is just how I do things and may not be the ideal way to handle formatting HTML. I just like to have my HTML nice and neat even when its mixed with PHP

The answer is, use templates.
If you properly separate your logic from your presentation, this question goes away. Your templates will have all the indenting or lack of indenting you want or need.
EDIT
Nonetheless, you can modify your code pretty simply:
<?php
function pagination($depth=0) {
$indent = str_pad("", $depth, "\t");
echo $indent."<ul>\n";
for($i = 1; $i <= 10; $i++)
echo $indent."\t<li>...</li>\n";
echo $indent."</ul>\n";
}
?>
<div>
<?php pagination(1); ?>
</div>
<div>
<div>
<?php pagination(2); ?>
</div>
</div>
Alternatively, you can just pass in the indent you want:
<?php
function pagination($indent="") {
echo $indent."<ul>\n";
for($i = 1; $i <= 10; $i++)
echo $indent."\t<li>...</li>\n";
echo $indent."</ul>\n";
}
?>
<div>
<?php pagination("\t"); ?>
</div>
<div>
<div>
<?php pagination("\t\t"); ?>
</div>
</div>

Edit: broke the code down into pages.
This code really only works with a template system.
Which can just be a basic:
// file: index.tpl.html
<html>
<head>
</head>
<body>
<div>Some header code</div>
<div>
{mainContent}
</div>
<div>Some footer code</div>
</body>
</html>
// file: functions.php
<?php
function pagination()
{
$output = "<ul>\n";
for($i = 1; $i <= 10; $i++)
$output = "\t<li>...</li>\n";
$output = "</ul>\n";
return $output;
}
function indent_html($html, $tag, $new_html)
{
// magic indenting code: finds how many spaces are used on the line above it
$spacePos = 0;
$find = strpos($html, '{'.$tag.'}' );
while( $html[ $find-$spacePos-1] == ' ' ) $spacePos++;
// Uses the indent from the line above to indent your new html
return str_replace("\n", "\n".str_repeat(" ", $spacePos), $new_html);
}
?>
// file: index.php
<?php
$html = file_get_contents("index.tpl.html");
// magic indenting code: finds how many spaces are used on the line above it
$spacePos = 0;
$find = strpos($html, '{mainContent}' );
while( $html[ $find-$spacePos-1] == ' ' ) $spacePos++;
// your pagination() needs to return html not output it
$mainContent = pagination();
$mainContent = indent_html($html, $tag, $mainContent);
// Uses the indent from the line above to indent your new html
$mainContent = str_replace("\n", "\n".str_repeat(" ", $spacePos), $mainContent);
// finally insert your html
$html = str_replace("{mainContent}", $mainContent, $html);
?>
Might need some modification if you want to use tabs instead of spaces.
I use spaces as it's more cross browser/application.

Related

Initializing the hidden input value with PHP [duplicate]

I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>

Call PHP variable in HTML

I wrote a code involving nested PHP and HTML parts as below. Why variable "v" is not displayed, But the variable "u" is?
<?php
$v= rand (1,15);
$u= rand (1,15);
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
<?php echo $v ?>
</body>
</html>
EOD;
echo $h;
?>
<html>
<body>
u=<?php echo $u ?>
</body>
</html>
PHP has two modes.
Inside <?php...?> (and other PHP tags) PHP code is evaluated
Outside those tags, code is streamed directly to the output
You have <?php echo $v ?> inside a PHP section (inside a string created with HEREDOC).
It doesn't trigger PHP evaluation of the content when the string is created because it is just part of the string. It doesn't trigger PHP evaluation when you later echo it because you are just echoing a string.
<?php echo $v ?> will be in the (invalid) HTML sent to the browser, and the browser will treat it as an unknown tag. The value of $v will be one of the attributes. The browser won't render anything for this unknown tab, but you will be able to see it in the Developer Tools Inspector or with View➝Source
Rethink your application design. Don't try to store strings containing PHP code. Generate the string with the data you need in it in the first place.
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
$v
</body>
</html>
EOD;
echo $h;

What is the best way to turn a HTML start and end tag into a function?

I have a complex HTML tag, with many attributes and it appears in very different parts of the code.
Example:
<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >
<some complex html code ... >
</div>
And I do not want to repeat this <div></div> with all its attributes in different parts of the code as it changes quite often during development.
If I create a function like this (example in PHP):
function myDivStart() { ?>
<div class="blabla" data-attribute="blablabla" data-another-attribute="blabla">
<?php }
then my resulting code would look like
<?php myDivStart(); ?>
<some html code ... >
</div>
and the finishing </div> would look kind of out-of-place, since there is no visual starting <div>. My text editor would also not parse this correctly and syntax highlighting is messed up.
Then, if I create another function for the closing </div>, it would be a very silly function indeed:
function myDivEnd() { ?>
</div>
<?php }
and turn the original code into
<?php myDivStart(); ?>
<some html code ... >
<?php myDivEnd(); ?>
This would solve the syntax highlighting problem, but it still feels very unclean to have such a silly function to close.
UPDATE: Storing the HTML code in a variable and passing that to a function would not really solve the problem neither, as the HTML inside a variable would not be parsed correctly with syntax highlighting.
$myHTML = 'A very long and complex piece of html';
<?php myDiv($myHTML); ?>
My text editor would not have syntax highlighting there.
And doing the following would also make the code disorderly, as the $myHTML code comes before the <div> and actually, logically belongs after it.
$myHTML = ?>
A very long and complex piece of html
<?php ;
myDiv($myHTML);
Is there any pattern that would solve for this?
If it's always the same tag you can use a variable or a constant instead of a function.
E.g.
$openTag = "<div class=\"blabla\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >";
$closeTag = "</div>";
If you have varying parts of that tag then you can instead indeed make a function, e.g.:
function openingDiv($class) {
return "<div class=\"$class\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >"
}
function closingDiv() {
return "</div>";
}
You can also make it a bit more sophisticated:
function wrapContentInDiv($content) {
return "<div class=\"$class\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >$content</div>";
}
Example uses:
<?php
$openTag = "<div class=\"blabla\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >";
$closeTag = "</div>";
?>
<leading html>
....
<?php echo $openTag ?>
<some html here>
<?php echo $closeTag ?>
...
<?php echo $openTag ?>
<some other html here>
<?php echo $closeTag ?>
<trailing html>
You can take this one step further and define your code in a separate php file:
e.g. config.php
Then you can:
<?php
require_once("config.php")
?>
...
Update:
You could also use a template e.g. file complexDiv.php
<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >
Use this as below:
<leading html>
....
<?php //Set any parameters that complexDiv.php needs here
include 'complexDiv.php'
?>
<some html here>
</div>
...
<?php include 'complexDiv.php' ?>
<some other html here>
</div>
<trailing html>
I suspect that before long you'll realise that its worth switching to a template engine like smarty of blade.
It depends on what the some HTML code is but you could do something like this pseudocode
$some_html=''; //your html code goes here as a string
myDiv($some_html);
function myDiv( $arg ){
echo <div class="blabla" data-attribute="blablabla" data-another-attribute="blabla">
echo $arg;
echo </div>
}
You can first prepare the HTML on a different file and include that file on the function where the div tags are waiting for them to wrap that content of yours. Hope it helps.
function wrapperDiv() {
$html = '';
$html .= '<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >';
$html .= include_once 'body.php';
$html .= '</div>';
return $html;
}
wrapperDiv();

PHP and HTML formatting, super basic question

I got to a phase in my code where I have too much code and too much HTML is depended on the consequences of some server conditions.
I simply want to know, is there any way to get around the:
<?php if (cond) echo '<p class="someclass">some HTML</p>'; ?>
?
I just wish there was something like in C where you can simply go like:
#ifdef x
do_a_lot_of_html_stuff;
#endif
All I can see that I can do now is go like:
<?php if (x) require_once("includes/all_needed_part.php"); ?>
Thanks !
Not exactly sure what you're asking, so if I am understanding your question correctly, you're looking for a way to print off blocks of HTML with PHP?
<?php if ($a == $b): ?>
<div>a == b</div>
<p>a is equal to b</p>
<?php else: ?>
<div>a != b</div>
<p>a is not equal to b</p>
<?php endif; ?>
I generally do it like this:
<?
function print_heading()
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><? print_title(); ?></title>
<link rel="stylesheet" type="text/css" href="..." />
<script language="javascript" type="text/javascript" src="..."></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="title" content="<? print_title(); ?>" />
</head>
<?
}
?>
But I would think that replacing function print_heading() with if (condition) would work too.
There's an alternative syntax:
<?php if($x): ?>
do_a_lot_of_html_stuff;
<?php endif; ?>
You can add HTML between PHP conditions as follows:
<?php
$a=1;
if($a==1){ ?>
<div>All the HTML Stuffs</div>
<?php } ?>
You may use the alternative syntax for control structures in combination with the heredoc-syntax.
You can do something like:
<?php if( cond ) { ?>
SECRET!
<?php } ?>
I would recommend that you check out a template engine, many exist for PHP with one of the most mature being Smarty. One of the newer (and cleaner) solutions is Twig, which is employed by the Symphony framework.
i guess you are at a point in your code where you should use Object Oriented Programming.
procedural coding is good but you'll eventually reach the point where there is just to much code in your page.
well you could use a c like syntax and still can do lots of stuff like.
This is typical php approach of using if using c like syntax.
<?php
if(1==1):
echo 'i can do lots of stuff here';
$variable = 'i hold some value';
$array = array('1','two','three');
endif;
?>
another way you could implement is by using brackets. for example.
<?php
if(condition) {
//do some stuff here
} else if(cond) {
//do another stuff here based on some conditions
} else if(cond) {
//you can extend the nested elseif as many times as you like
} else {
//else execute this.
}
?>
Guessing you are asking if there are frameworks available for php? The answer is yes, and here is at least one good one: http://cakephp.org/

How can I echo HTML in PHP?

I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>

Categories