So, why does this work:
<?php if (condition): ?>
<!--html code here-->
<?php endif; ?>
But not simply this:
<?php
if (condition) { ?>
<!--html code here-->
<?
}
I figured it was just style preference, but I actually can't seem to get it to work the second way. Am I just doing something completely wrong? I can't see the purpose of outputting HTML right in the middle of an if statement if you wanted it to always print.
You need to allow short tag in your php.ini to make <? work
else you have to write <?php } ?>
The second way should work like you described considering you have the closing php tags and < ?php
It does, if you have the right re-opening tag...
<?php
if (condition) { ?>
<!-- html code -->
<?php
}
Related
I'm not very experienced at php, so if there's an easy function for this, I'll feel like an idiot.
When coding in PHP, at the point where you need to echo some HTML code, I have found I have either one of two options.
A: echo "<!--html text here-->";
B: echo "\t\t\t<!--html text here-->\n";
If I were to use method A throughout the code, looking at the php code from client side using view-source produces a solid block of code which is difficult to read.
If I were to use method B, it looks fine client-side, but the actual source code looks messy.
Is there anyway to keep both server and client-side appearance clean?
Something like this
<?php
//php code here
?>
//html code
<h3> <?= $justADynamicVariable ?> </h3>
<?php
//continue php code
?>
Un-readable front end code is caused by poor factoring of your PHP code
The wall-of-text issue occurs because your code is messy. You have logic and display code in the same place (evident from the fact that you're echoing HTML from a PHP block) and this will always produce unreadable and ugly code.
Look at Model-View-Controller pattern, and separate out your logic code from your display code. Then, write your display code in a primarily HTML format with some in-line PHP:
<div>
Welcome back <?= $this->username; ?>
</div>
If you're having to echo HTML code from a PHP block, your code is probably factored wrong.
Other useful tricks to produce readable code:
Use alternative PHP control blocks
This:
<div id='somediv'>
<?php if($something): ?>
Some stuff
<?php endif; ?>
</div>
is infinitely more readable than this:
<div id='somediv'>
<?php if($something) { ?>
Some stuff
<?php } ?>
</div>
And it's definitely better than this which is probably what you're using now:
<?php
echo "<div id='somediv'>";
if($something) {
echo "Some stuff";
}
echo "</div>";
?>
You can just close the php tag (?>), write the html block and return to php (
Use a templating engine, like Twig http://twig.sensiolabs.org/ it allows you to separate your logic out of your templates so you can write really easy to markup with simple syntax to drop in dynamic variables.
or
Use a browser like Chrome, which will auto indent your source for you when you use the Web Developer Tools http://discover-devtools.codeschool.com/. You can even copy paste the results really quickly to a new file. In general, it's a bad idea to fret over outputting well spaced html since software can clean it up so easily.
There are lot's of ways to produce html, depending or it's a single line or an entire block of HTML.
The important thing is readability.
echo "<div><p>Hi ".$name."</p></div>";
Isn't unreadable persé, it might be annoying because it won't get highlighted in many IDE's.
This is a good reason to always seperate html and php, meaning always put html parts outside of your php tags.
So you could end your php block before and open it again after :
if(TRUE) {
?>
<div><p>Hi <?php echo $name;?></p></div>
<?php
}
If you have PHP within a large file mostly containing html you are better of using php control blocks:
<!--html text here-->
<?php if(TRUE):?>
<div>
<p>Hello <?php echo $name;?></p>
</div>
</php endif;?>
<!--html text here-->
You could also use heredoc
echo <<<EOD
<div>
<p>This is html</p>
</div>
EOD;
Or output buffering:
ob_start();
?>
<div>
<p>Hello <?php echo $name;?></p>
</div>
<?php
$html = ob_get_clean();
echo $html;
I'm fairly new to PHP. I started learning it like 3 weeks ago. I cannot find the answer to this question on StackOverflow, Google or Youtube. The PHP documentation to this just confuses me. To get on with the question, how does PHP code mixed in with HTML work?
<?php if (something) { ?>
<p>Hello</p>
<?php } ?>
The p element will only display if something has a truthy value, how is this?... I thought for sure that the PHP engine ignored what was going on around the outside of the codeblocks (e.g. <?php ?>) and only parsed what happens on the inside.
The code below gets parsed by the PHP engine normally and sent to the browser without affecting any HTML elements (even though its clearly between 2 code blocks).
<?php echo $something; ?>
<p>Hello</p>
<?php echo $something; ?>
I hope I'm not going to get flamed for asking this question since a lot of people seem to understand how it works in like a tenth of second.
P.S. I asked this question in chat early and thought I understood it correctly but when I went to implement it my mind was still like, how does this work exactly? It just seems like some kind of hack to me.
Easy now. Definitely need a php tutorial for you to start on http://www.tizag.com/phpT/
Here is what your doing:
<?php
//Anything inside me php processes
if($something)
{
echo "<p>something</p>";
}
//About to stop processing in php
?>
<p>Anything outside of the php statement above will just be printed to the dom</p>
Quick Note: It is good practice to separate your PHP from your HTML
<?php if ($something) { ?> <-- where is the other {
<p>Hello</p>
<?php } ?> <-- oh I see it.
In your first example it is indeed true that <p>Hello</p> will be rendered if and only if 'something' returns true.
If you close a php tag with ?> but have an 'unclosed' execution, like if (blah) { ..., the PHP engine understands your desires and does accordingly.
Why?
The PHP engine is kept 'waiting' until the execution is closed with } and then the final result is evaluated and the browser continues on with the lines below.
Obviously if you leave out the final } you will see some errors, which tells you that PHP was expecting you to finish what you started and you did not
Both the php and html are parsed in-line. So, as it moves down your script it will run php scripts within tags, and display html in the order which they are placed. For example:
<? $someVar = "someVar string value"; ?>
<h1>This is a title</h1>
<? if(1 == 1){?>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<? } ?>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: <?=$someVar;?></p> // <?= is a short hand for echo
This will show as:
<h1>This is a title</h1>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: someVar string value</p>
Basically just think of it as the server reading down your script and parsing whatever it sees as it goes. If there is html, it will display it and if there is php which does some sort of calculation and then spits out html, it will show the spat out html.
You can write php code anywhere in HTML using php code block
<?php echo "whatever " ?>
or
<?php echo "<h1>Here everything will displayed in h1 </h1> "; ?>
and if you use control structure ( if, switch etc.. ) then it will behave like all other languages, means if something is true then it will execute the part written between { }.
so if you write an undefined variable in if condition then it will not execute code block of because undefined variable is treated as false condition .
additionaly you can check any variable value by var_dump($variable)
PHP's Alternative syntax for control structures
<!DOCTYPE html>
...
<div>
<?php if ( the_thing === true ) : ?>
<p>The thing is true! \o/</p>
<?php else if ( the_other_thing === true ) : ?>
<p>The other thing is true! meh</p>
<?php else : ?>
<p>Nothing is true :-(</p>
<?php endif; ?>
</div>
...
I have a bunch of php files that I want to incorporate html (divs) and css (external stylesheets) elements into.
If any one has any tips / ideas on how to go about doing this I'd love to hear them :)
You could either :
Integrate HTML code in your PHP file,
Or have your PHP script echo the HTML content.
With the first solution, your PHP file could look like this :
<?php
$var = 10;
// some PHP code
?>
<div>
this is some HTML
</div>
<?php
// and some PHP code again
?>
For more informations about this, see the following section of the manual : Escaping from HTML.
While, with the second solution, your PHP file could look like this :
<?php
$var = 10;
// some PHP code
echo '<div>this is some HTML</div>';
// and some PHP code again
?>
Basically, you are free to mix HTML and PHP code in the same PHP script : outside of <?php ... ?> tags, things will not get interpreted as PHP code.
All you need to do is exit php and write html as normal:
<?php
// php code
?>
<div>
<p>Some html</p>
</div>
<?php
// more php code
?>
Take a look at the PHP alternative syntax for control structures. It is often times more comprehensive when you start mixing with plain HTML:
<?php if(...): ?>
<p>paragraph</p>
<?php endif; ?>
Instead of:
<?php if(...) { ?>
<p>paragraph</p>
<?php } ?>
I got this code below from a tutorial I'm using to learn PHP. I know that // is used to comment out code. In the first line of the code below, you see {// subject selected ?>
Is the php tag ?> not commented out by the // along with the subject selected text?
<?php if (!is_null($sel_subject)) {// subject selected ?>
<h2><?php echo $sel_subject['menu_name'];?></h2>
<?php } elseif (!is_null($sel_page)) {// page selected ?>
<h2><?php echo $sel_page['menu_name']; ?></h2>
<?php } else { // nothing selected ?>
<h2>Select a subject or page to edit</h2>
<?php } ?>
the BEST place to address such questions is an official man page:
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that.
I can assure you that it's way more reliable source of knowledge than some volunteered help from some enthusiast
No, ?> is not commented out.
no ?> are not commented out with the in line comment, where as the block comment they are.
http://codepad.org/YUhG2DTd
Example: The following ?> does not get commented out.
<?php
\\?>
echo 'works';
?>
where as the following does get commented out.
<?php
/*
?>
*/
echo 'failed';
?>
{// subject selected ?>
No, the ?> is not commented. Because, that is not part of a php statement. That is a tag that apache uses to determine. Apache will send the contents enclosed by the tags to php and place the output from php in its output buffer.
I am new to php and wondering if I can have something like this:
<?php
...
magicFunctionStart();
?>
<html>
<head>...</head>
<body>...</body>
</html>
<?php
$variable = magicFunctionEnd();
...
?>
What I have to use right now is
<?php
...
$variable = "<html><head>...</head><body>...</body></html>"
?>
Which is annoying and not readable.
Have you tried "output buffering"?
<?php
...
ob_start();
?>
<html>
<head>...</head>
<body>...<?php echo $another_variable ?></body>
</html>
<?php
$variable = ob_get_clean();
...
?>
I think you want heredoc syntax.
For example:
$var = <<<HTML
<html>
<head>
random crap here
</html>
HTML;
I'm not really sure about what you are trying to accomplish, but I think something like the heredoc syntax might be useful for you:
<?
$variable = <<< MYSTRING
<html>
<head>...</head>
<body>...</body>
</html>
MYSTRING;
However if you are trying to make HTML templates I would highly recommend you to get a real templating engine, like Smarty, Dwoo or Savant.
Ok what you want to do is possible in a fashion.
You cannot simply assign a block of HTML to a php variable or do so with a function. However there is a number of ways to get the result you wish.
Investigate the use of a templating engine (I suggest you do this as it is worth while anyway). I use smarty, but there are many others
The second is to use an output buffer.
One of the problems you have is that any HTML you have in your page is immediately sent to the client which means it cant be used as a variable in php. However if you use the functions
ob_start and ob_end_fush you can achive what you want.
eg
<?php
somesetupcode();
ob_start(); ?>
<html>
<body>
html text
</body>
</html>
<?php
//This will assign everything that has been output since call to ob_start to your variable.
$myHTML = ob_get_contents() ;
ob_end_flush();
?>
Hope this helps you can read up on output buffers in php docs.
I always recommend to AVOID buffer functions (like ob_start ,or etc) whenever you have an alternative (because sometimes they might conflict with parts in same system).
I use:
function Show_My_Html()
{ ?>
<html>
<head></head>
<body>
...
</body>
</html>
<?php
}
...
//then you can output anywhere
Show_My_Html();
$html_content = '
<p class="yourcssclass">Your HTML Code inside apostraphes</p>
';
echo $html_content;
Its REALLY CRAZY but be aware that if you do it :
<?php echo ""; ?>
You will get it:
<html><head></head><body></body></html>
Keep calm, its only php trying turn you crazy.