I often use HTML template for my application and within the template content there are place holder which I marked as <?php echo $myVar; ?>
Is there a shorter syntax for that? I tried <?php=$myVar?> but didn't work :D
Please give a hint if you know some way. Thank you!
<body>
<?php $myVar = 122; ?>
abb
<div>
<?php echo $myVar; ?>
</div>
<div>
<?php=$myVar?>
</div>
ccc
</body>
<?=$myvar ?>
short_open_tag should be On.
You can use short tags if enabled.
<?= $var; ?>
This is the same as doing this:
<?php echo $var; ?>
To set this up you can find info here, however it's not recommended you use this method.
http://php.net/manual/en/ini.core.php
If ASP tags are enabled you can also do things like this:
<%=$var; %>
<% echo $var; $>
The shorter version is <?=$myVar;?>, but please DON'T do this! :(
Quoting from the comment, in case anyone misses it.
because:
This will not allow much flexibility in moving the servers, i.e. you must control the server or be allowed to change the ini
directives [to turn on short_open_tag], otherwise you are doomed.
It might be deprecated in the future.
Readability is not a trade for functionality. Period.
it is
<?=$myVar; ?>
short tag should be enabled with PHP
If you are going to use inline xml with PHP do not enable short tags.
As documented here
If you want to use PHP in combination with XML, you can disable this
option in order to use inline. Otherwise, you can print it
with PHP, for example: '; ?>. Also,
if disabled, you must use the long form of the PHP open tag ().
You could use double quote echo like this:
<?php
$myVar = 122;
echo "
<body>
abb
<div>
whatever and $myVar displayed here
</div>
<div>
The content is: $myOtherVar
</div>
sometext
</body>
";
?>
But consider using your template with OOP. It would be even cleaner:
Template::header();//Echoes your template header
Template::content($myContentText,$myWhateverVar);//Echoes your template filled with your vars
HTH,
caffein
Related
Rookie here, so please correct me if I have anything wrong.
So here's a snippet of my HTML:
<html><body>
<h2>Home Page</h2>
Welcome back <?= $fgmembersite->UserFullName(); ?>!
</body></html>
The function, $fgmembersite->UserFullName(), returns a string (100%, if I call the function within tags it prints out correctly). How do I get it to echo out in the HTML?
I think an alternative would be to echo the entire HTML code, and I think it'd work then, but I don't want to do it that way because I read somewhere that echoing all of your HTML is bad. Could somebody also confirm/deny that?
Right now, this is what shows on the site:
Welcome back UserFullName(); ?>!
No idea why
Thanks for your time!
I think you want the code to look like this...
Welcome back <?php echo $fgmembersite->UserFullName(); ?>!
This will ECHO the result of the function call.
What you are seeing is the result of the browser trying to parse the PHP. It is trying to treat <?= $fgmembersite-> as an unknown tag and then renders the rest as text.
There are two possible reasons for this:
You need to pass it through a PHP engine first.
You need to access the file through a web server which supports PHP and is configured to run your file through PHP when it is requested (typically this is done by using a .php file extension).
Note that installing a web server then double clicking a PHP file in your file manager isn't sufficient - the browser will just load the file from the file system. You need to type http://etc etc.
It is also possible that you have short_open_tag disabled (which is common and sensible) and are using PHP 5.3 or older (which isn't a great idea, 5.3 is still supported but it is the oldest branch that is).
If this is the case, your options are:
Upgrade PHP
Use <?php echo ... ?> instead of <?= ... ?>
Enable short_open_tag
Can't you just do
<?php echo $fgmembersite->UserFullName(); ?>
?
use it as follows:
<html><body>
<h2>Home Page</h2>
Welcome back <?php echo $fgmembersite->UserFullName(); ?>!
</body></html>
Do you have short_open_tag enabled on your server? You need to have that enabled to use that syntax. If you don't have that, use <?php echo $fgmembersite->UserFullName(); ?> like the other users suggested.
You can check the setting on you server by creating a file containing <?php phpinfo(); in it, and accessing that.
Also, echoing all your HTML inside the <?php tags are considered a bad practice because you should separate your business logic and your HTML. Echoing HTML directly from inside the PHP tags quickly leads to a mix of HTML and PHP, and it will be harder to read (for others, and yourself later on)
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 using PHP to make my page more dynamic through query passing however I have a big chunk of HTML code that needs to have dynamic content inside but I don't know how to go about doing that without printing every statement:
One part in HTML:
<div class="review">
<p>
<img src="http://www.cs.aub.edu.lb/hsafa/cmps278/hw2/rotten.gif" alt="Rotten" />
<q>Expect no intelligence or subtlety here, but if you're willing to put up with the sheer ridiculousness of it all, you might enjoy wallowing in Bekmambetov's shameless exhibition of narrative lunacy and technical fireworks in this movie.</q>
</p>
</div>
<div class="personal">
<p>
<img src="http://www.cs.aub.edu.lb/hsafa/cmps278/hw2/critic.gif" alt="Critic" />
Frank Swietek <br />
<span class="italic">One Guy's Opinion</span>
</p>
</div>
The above code is for a single review however there could be any number of reviews which I am already taking a count of but I am also changing the image, quotes and text for all the reviews.
Is there a way of including all the tags without printing them all?
The regular way is to "close the php tag" and then reopen it after the HTML:
// php code here
?><html code goes here><?php
// php code here
However, there are a couple other ways. One is to use include.
// php code here
include('template.file.php');
// php code here
and inside your html code, you use have something like this:
<htmltag><?= $php_value ?></htmltag>
You can even use include within a function.
Alternatively, you can use a template system like Handlebars, Mustache, or Twig. Or you can just continue to build large strings, which is what I do. I set up templates, merge them with data to produce strings, and then emit the strings. The main thing I gain from using the templating system is that I can save up the strings to emit them at the end, and thus, have the ability to alter the HTTP header before my output is sent. If I used include() or code blocks, the code is emitted immediately, and I cannot modify HTTP header values.
Additionally, by building up the strings, I can save them to files and use these precalculated chunks to improve the site's speed.
<?php
//PHP code section
$wolrd = 'world';
?>
We are back in HTML
Hello <?= $world /* and some PHP echoing with a 'short tag' on same line with HTML*/ ?>
Suggested reading:
http://www.smarty.net/ (I'm not a fan but you should be aware of it)
MVC - Model - View - Controller
You should only be using PHP to print your dynamic content
<img src="<?php echo $image_url; ?>" alt="<?php echo $image_alt; ?>" />
You can close PHP and start it again at any point
<?php
$string = "hi";
?>
<p>Lot's of HTML</p>
<?php
echo $string;
?>
I am working with levels of security with my app and i have written a function that simply checks - depending on it's session user id what kind of priviligies he/she has. It works fine but in some pages i want to output some information if the user is superuser, and forbid to output information if user is a guest.
I do it with such a syntax:
1. <? if admin('superuser', $_SESSION['user_id']) { ?>
2. <div></div>
3. <? } ?>
It works good but it's not elegant, and in case long code between curling brackets it messess with purity of my code.
Is there a way to "alias" a line 1 and 3 to some kind of shortcut, ie
1. <? admin_superuser ?>
2. <div></div>
3. <? admin_super_user_end ?>
Maybe you have some other ideas to perform such levels of security?
The idea came from ob_start() and ob_end() commands.
I am waiting for your ideas.
Kalreg.
you could simply set a bool at the beginning of the page:
$isSuperUser = admin('superuser', $_SESSION['user_id']);
Then, just do
<? if ($isSuperUser) { ?>
<div></div>
<? } ?>
If you don't like the $, you could define a constant:
define("SUPERUSER", admin('superuser', $_SESSION['user_id']));
Then, just do
<? if (SUPERUSER) { ?>
<div></div>
<? } ?>
Good thing about a constant is that it is global, and if using in a function, you wouldn't have to declare it global first, or pass it as an argument.
I would go with something like this. I think this totally acceptable.
To simplify it you just need a wrapper for your user.
<?php if ($user->isAdmin()): ?>
<div></div>
<?php endif; ?>
you can include another php file that contains the corresponding html / php code with the "include" function. i also recommend to use <?php instead of just <? due short open tag issues with xml and ini settings.
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.