How to echo lots of HTML between an IF statement - php

At the moment my PHP code is like this:
<?php
some code
?>
lots of HTML
<?php
some more code
?>
I now want to include large chunks of HTML depending upon the values of certain PHP variables so like this:
<?php
if ($requiresSignature===true) {
echo "some HTML";
echo "some more HTML";
}
?>
Using echo is fine for a few lines of HTML but is there an easier way when I've got maybe 500 lines of HTML so I don't have to type echo in front of each line?

You can do it this way
<?php
if ($requiresSignature===true) {
?>
<b>some HTML</b>
<b>some more HTML</b>
<?php
}
?>

For this usage, the heredoc or nowdoc functionalities of php are the best options, in my humble opinion.
Heredoc
Heredoc is like echo "Foo bar"; but intended for a large chunk of text, spanning multiple lines.
Like this:
echo <<<FOO
<h1>Foo bar</h1>
<p>Lorem ipsum dolor sit tenet conseqteur...</p>
<i>Created by $name</i>
FOO;
This syntax is also available for setting variables, class properties, class constants and static variables (since php 5.3). The FOO part, you can set yourself. Just remember to close the Heredoc with the same ending on a line by itself (with absolutely no indentation), ended with a semicolon.
E.g.
$foo = <<<BAR
This is an example text.
Spanning multiple lines.
BAR;
Nowdoc
Think of Nowdoc as the ' equivalent of ". That is, no variable substitution is performed inside a Nowdoc statement, just like none is performed inside a 'single quoted string'.
The syntax is like this:
echo <<<'EXAMPLE'
This
is
a
test
EXAMPLE;
In conclusion I would do like this:
if ($requiresSignature===true) {
echo <<<HTML
Some html<br/>
And even more <b class="html">html</b>
HTML;
}

echo '
some html
some html
some html
';
I think that's what you're looking for

Try this
<?php
if (true){
?>
pure html code here
<?php
else{
?>
pure html code here

Try this
<?php
$Html = '';
if ($requiresSignature===true) {
$Html .="some HTML";
$Html .="some more HTML";
echo $Html;
}
?>

You can use heredoc syntax: See more detail in here
echo <<<"MYHTML"
html
lots of html
MYHTML;

this work for you
<?php if( var == true ): ?>
<p>Your HTML</p>
<?php endif; ?>

It's useful, try this code:
<?php
if ($requiresSignature===true) {
$var = "some HTML";
$var .= "some more HTML";
echo $var;
}
?>
**OR**
<?php if ($requiresSignature===true) { ?>
HTML CODE
<?php } ?>

Try this method,
<?php
$Html = "";
if ($requiresSignature===true) {
$Html .="some HTML";
$Html .="some more HTML";
echo $Html;
}
?>

You Don' Need to write echo to each line.
You Should use :
echo '
some html
some more html
some more html
';

PHP is a HTML embed language.You can try it every where of your php page.
<?php if ($requiresSignature===true): ?>
<p>"some more HTML"</p>
<?php endif;?>

...but is there an easier way when I've got maybe 500 lines of HTML so I don't have to type echo in front of each line? It turns out there is, so yes and here is how:
<?php
$myString = "PHP is so cool...";
if($requiredSignature === true):
?>
<div class='too-much-html-markup'>
All the RAW HTML MARKUP here would only be displayed if (and only if)
the condition above evaluates to true so i don't have to worry about
any kind of echoing. However, i can still go ahead and echo some
content here if i still choose like this: <?php echo $myString; ?>
And everything will still work out just fine.
</div>
<?php else: ?>
<div class='still-some-raw-html-in-else-clause'>
Again this is a raw Markup and will only be rendered if the IF
condition above evaluates to FALSE!
</div>
<?php endif; //<== NOW I END THE CONDITIONAL LOGIC WITH endif KEYWORD ?>

variables output in the plain HTML, consider doing so like this:
<?= $variable ?>
or
<?php echo $variable; ?>

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>

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();

Output some PHP code into a HTML <code> tag

How can I use the HTML <code> element to output a block of PHP code, without the page running that PHP code? Eg;
<pre><code>
<?php
// Some super duper PHP code
?>
</code></pre>
I'm creating an API docs page, which features snippets of PHP that anyone wishing to use the API can use as examples, but anything wrapped in <?php> tags runs as an actual PHP function
Use <?php and ?>.
The HTML entities will show up as PHP opening and closing tags when the page is rendered, but PHP will obviously not see them. But you have to html-escape your code anyways, otherwise contained HTML-tags will be rendered. So there should be
<?php echo 'Hello, World.<br>'; ?>
Another way would be to have a string specified by a nowdoc and then output html-escaped (demo):
<?php
$code = <<<'EOC'
<?php
echo 'Hello, World.<br>';
// ...your code here...
?>
EOC;
echo htmlentities($code);
?>
Have look for different approaches at How do I display PHP code in HTML?.
Do this via PHP like so:
<?php
$code = '<?php
echo "Hello, World!";
?>';
echo '<code>' . htmlspecialchars($code) . '</code>';
?>
try something like this:
<?php echo '<?php'; ?>
This may help you.........
######################################################################
echo "<h2><br>Source Code of ".basename((string)__FILE__) . "</h2><hr>";
show_source(__FILE__);
echo "<hr>";
echo "<h2>Output of ".basename((string)__FILE__) . "<hr></h2>";
#######################################################################
I had to convert the less-than and greater-than to their HTML name.
<pre><code><?php echo
"<!--
This is the church title to be used in the heading of the web-pages.
Author: John Fischer III of Written For Christ in 2018
Updated:
-->
<?php echo 'Our Little Church:'; ?>" ?>
</code></pre>

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>

PHP: Breaking out of PHP for HTML but return as value instead of print on page?

I am generating a lot of HTML code via PHP, but I need to store it in a variable, not display it immediately. But I want to be able to break out of PHP so my code isnt a giant string.
for example (but actual code will be much larger):
<?php
$content = '<div>
<span>text</span>
link
</div>';
?>
I want to do something like this:
<?php
$content =
?>
<div>
<span>text</span>
link
</div>
<?php
;
?>
But I know this will not return the html as a value it will just print it to the document.
But is there a way to do this tho?
Thanks!
You can use output buffering:
<?php
ob_start();
?>
<div>
<span>text</span>
link
</div>
<?php
$content = ob_get_clean();
?>
Or a slightly different method is HEREDOC syntax:
<?php
$content = <<<EOT
<div>
<span>text</span>
link
</div>
EOT;
?>
Try this:
<?php
$var = <<<EOD
my long string
EOD;
echo $var;
?>
(edit done, but one has edit faster than me :))
In my opinion, you should look into a template engine such as Smarty. It can help you take some of the ugliness out of hardcoding HTML into the PHP file, and can help make the code more manageable.
You could store the html in an html file and read that file into a variable.
While still technically a string, you might find the documentation on PHP's heredoc to be an entertaining read:
heredoc syntax
$content = <<<EOT
<div>
<span>text</span>
link
</div>
EOT;
Use heredoc syntax.

Categories