PHP usage easy for template's - php

Actually i once saw some PHP code on php.net but i forgot its name or usage.
It is something may be related to heredoc (may be not)
What i am trying to achieve is to do HTML inside php IF conditions..
it was somthing like
xhtml code here
i hope u understand what i am trying to ask!
thanks for your help.

If you're referring to the alternative syntax for control structures, it's something like this:
<?php if ($a == 5): ?>
<div>A is equal to 5</div>
<?php endif; ?>
Reference: http://php.net/manual/en/control-structures.alternative-syntax.php

http://php.net/manual/ru/language.types.string.php#language.types.string.syntax.heredoc
http://php.net/manual/en/function.ob-get-clean.php
<?php
/** Other PHP code */
$is = true;
?>
<?php ob_start(); ?>
<h3>Caption</h3>
<?php if($is): ?>
...some text 1
<?php else: ?>
...some text 2
<?php endif; ?>
<?php $out = ob_get_clean(); ?>
<?php
/** Other PHP code */
echo $out;
?>

Related

open&close php tags on each line, within arrays, functions

I collaborate with a web-programmer on a php project based in kirby cms, and he wants to open and close every line as such:
<main>
<?php /*php code here/* ?>
<?php /*more php here*/ ?>
...
Trying to follow this style, I found some errors in my code. The first is that it seems I canNOT do this in the middle of an array as such:
BAD CODE
<?php $oo = array( ?>
<?php 'h' => 100, ?>
<?php 'v' => 100, ?>
<?php ); ?>
but I can do it in the middle of a foreach loop as such:
<?php foreach ($p as $subp): ?>
<div id='<?= $subp->title() ?>'>
<?php endforeach; ?>
Are there any other cases such as array in which I canNOT do this?
/edit
According to the answer, there can only be tag-breaks within 'foreach', 'while', or 'if' blocks.
How about a 'foreach', 'while' or 'if' within a function? is that 'legal'?:
<?php
function myFunction($arg){
if($arg === 'this'): ?>
<?= '<p>yep</p>' ?>
<?php else: ?>
<?= '<p>nop</p>' ?>
<?php endif;
};
?>
And how about nesting if within foreach within function?:
<?php
function myFunction($arr){
foreach($arr as $val): ?>
<p><?= $val ?> <p>
<?php if($val === 'this'): ?>
<?= '<p>yep</p>' ?>
<?php else: ?>
<?= '<p>nop</p>' ?>
<?php endif;
endforeach;
};
?>
edit/
Thank you
you cannot "break out of php" mid statement. wline defining an array for example you cannot close the php tags. The only time when you can "break out" of php is between opening and closing a loop or an if/else statement. This actualy does not break the statement as <?php foreach: ?> is a complete statement whereas <?php foreach{ ?> is not. Here some examples of what you can do:
<?php if($this!=$that): ?>
{something}
<?php endif ?>
<?php foreach($things as $thing): ?>
{something}
<?php endforeach ?>
<?php $while($this): ?>
{something}
<?php endwhile ?>
I think you get the message. you must have complete statements within php tags, without interruptions.
P.S. Also avoid using the shorthand <? instead of <?php at all cost, moving your project to a different hosting or an upgrade of your hosting might break your project as per default short tags are not activated. <?= ?> shorthand is safe as this is unaffected by the setting for newer php versions.
P.P.S Do not listen to the guy who wants php in one line, this will make your code hard to read and maintain. Stand strong and write beautiful code :)
UPDATE: (after the update on the question from #Jaume Mal)
I did not mean the examples in my answer as exclusive but as examples of statements that are complete vs statements that are incomplete. (I also forgot to mention closing php tags mid fuction, wich also work but I despise and woudl strongly advise against.) So for example <?php function foo(){ is a complete statement of starting a function but (as the other cases with loops etc..) it needs a closing statement, in this case }. This is true for if / else or foreach and so on:
<?php if($this){ ?>
some code
<?php } ?>
is a valid code, as the code pieces within the php tags are complete statements.

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

How to echo lots of HTML between an IF statement

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

$string is not showing in common.php

Let's say I've got 2 files. 1 is common which loads all the design and stuff and one is index.
What I want to do is set a $ in index like this:
<?
$SubId3 = 'test';
include "../../common.php";
?>
Then in common I want to have something like
<?=$SubId3; if (empty($SubId3)) { echo 'homepage'; } ?>
I cannot seem to get this working. Meaning if I set it up this way. The index will never show "test".
What am i doing wrong here?
I want to do this since only certain files will contain the string $SubId3, to test some things on certain pages and not others (by adding $SubId3 = 'test'; to that particular file)
Note that <?= is short-hand to output something (think of <?= as <?php echo) and not to execute any other sort of logic or code.
However, it is possible to use the ternary operator this way:
<?= empty($SubId3) ? 'homepage' : $SubId3; ?>
This is basically equivalent to this:
<?php
if (empty($SubId3)) {
echo 'homepage';
}
else {
echo $SubId3;
}
?>
So the <?= short-hand should only be used to pass one simple variable or a ternary expression to it; everything else should use the common <?php tag.
Here's a test case for Alex (in the comments) because I can run the above code just fine with PHP 5.4.12, but he seems not to be able to.
common.php
<?= empty($SubId3) ? 'homepage' : $SubId3; ?>
index.php (visit this file then)
<?php
$SubId3 = 'test'; // <-- Comment this out for the "homepage" output
include 'common.php';
i think this
<?=$SubId3; if (empty($SubId3)) { echo 'homepage'; } ?>
should be
<?php $SubId3; if (empty($SubId3)) { echo 'homepage'; } ?>
<?=?> is short for <?php echo?>
This wont work:
<?=$SubId3; if (empty($SubId3)) { echo 'homepage'; } ?>
If you want to print some stuff, you have to use only the variable, in one block and the IF on another.
<?=$SubId3?>
And:
<?php if(empty($SubId3)) { echo 'homepage'; } ?>
Hope this helps...
Try
<?php
/* echo $SubId3; */
if (empty($SubId3)) {
echo 'homepage';
} else {
echo $SubId3;
}
?>
Consider using different style of coding.
In PHP you have generally three variants:
PHP code only
HTML files with just some echoes
Intermixed PHP and HTML
In first you use echo to output every single bit of the HTML.
Second means you include a PHP script at the top of your HTML file and call appropriate functions / insert text into the template. Just so you can edit your HTML separately from your PHP.
Third makes for sometimes unreadable and complex code, but is fast to write.
<?php if($something) {
while($otherthing) { ?>
<B>text=<?=$index ?></B>
<?php }} ?>
Just a food for thought.
I found the answer guys, thanks for all the help.
I needed to set it in the PrintHeader like this:
<?
include "../../common.php";
printHeader('BlogNr1', 'BlogNr2', 'BlogNr3');
?>
And the index had to look like this:
<?
include "../../common.php";
printHeader('BlogNr1', 'BlogNr2', 'BlogNr3');
?>
Somebody on skype helped me. thanks anyways guys!

Is there harm in outputting html vs. using echo?

I have no idea really how to say this, but I can demonstrate it:
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
vs
<?php if (true) { ?>
<h1>Content Title</h1>
<?php } ?>
What differences are there between the two? Will there be problems caused by not using echo? It just seems super tedious to write echo "html code"; all the time, specially for larger segments of html.
Also, bonus kudos to someone who can rephrase my question better. :)
There's a small difference between the two cases:
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
Here, because you're using double quotes in your string, you can insert variables and have their values rendered. For example:
<?php
$mytitle = 'foo';
if (true) {
echo "<h1>$mytitle</h1>";
}
?>
Whereas in your second example, you'd have to have an echo enclosed in a php block:
<?php if (true) { ?>
<h1><?php echo 'My Title'; ?></h1>
<?php } ?>
Personally, I use the same format as your second example, with a bit of a twist:
<?php if (true): ?>
<h1><?php echo $mytitle; ?></h1>
<?php endif; ?>
I find that it increases readability, especially when you have nested control statements.
There are no relevant differences performance-wise. But you won't be able to use variables in the latter, and it looks less clean IMO. With large blocks, it also becomes extremely difficult to keep track of {} structures.
This is why the following alternative notation exists:
<?php if (true): ?>
<h1>Content Title</h1>
<?php endif; ?>
it's marginally more readable.
This:
<?php if (true) : ?>
<h1>Content Title</h1>
<?php endif; ?>
This is the way PHP is supposed to be used.
Don't echo HTML. It's tedious, especially because you have to escape certain characters.
There may be slight performance differences, with the above probably being faster. But it shouldn't matter at all. Otherwise, no differences.
I appreciate all the feedback. :)
I did find out some issues when using the two different methods.
There does not appear to be any real issue here except that the formatting looks terrible on the source and the tedious nature of it.
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
Using php this way can cause an error as such
Warning: Cannot modify header information - headers already sent
<?php if (true) { ?>
<h1>Content Title</h1>
<?php } ?>
The headers error can possibly be solved by using php like so
<?php ob_start(); if (true) { ?>
<h1>Content Title</h1>
<?php } ob_end_flush(); ?>
As to why and when the headers are sent, I am not completely sure...

Categories