PHP output in HTML file - php

Ay guys,
I do know two possibilites to display PHP in HTML:
<?php function(); ?> or the shorter method <?= function(); ?>
But I often see something like {METHOD} or {OUTPUT} in the HTML part of bigger scripts f.e.:
<div class="test">{OUTPUT}</div>
In my opinion this is a way tidier. Could somebody tell me more about this?

I have used php to generate html using the echo function and have used php inside html too.(If this clarifies your doubt in anyway)
echo $projectname; inside html file tags
echo the html file
Cheers :)

When echoing data in HTML without a template engine, short tags are preferred as they look cleaner, and are easier to read. They're great when using control structures too: http://php.net/manual/en/control-structures.alternative-syntax.php
For short tags to work short_open_tag needs to be enabled.
The example you shown with the curly brackets is usually specific to a template engine such as Twig.

you can use this method only with the function ECHO with double quotes :
1 - this works
$name = 'Mark';
echo "<div>GoodMorning {$name}</div>";
2 - this does not work
$name = 'Mark';
echo '<div>GoodMorning {$name}</div>';

Related

What are some good tips for writing php files along side raw html?

I do not like spitting back html with php's echo, makes it hard to do and read nested elements. So I usually write conditions that write raw html and make it as readable as possbile when editing the file directly or viewing the output html through the browser. However, I cannot find a style that stays readable for long. Any suggestions?
<?
if($foo == $bar)
{
?>
<div>
<p>hello, world</p>
</div>
<?
}
?>
As you can see, it doesn't look too good. At least not to me, but it makes the browser output more readable so I can better check the it for any mistakes.
i dont want this:
<?
if($foo == $bar)
{
echo "<div>\n\t<p>hello, world</p>\n</div>\n";
}
?>
Is my approach incorrect to begin with? should I use php to output to a .html file? and just view from the browser for mistakes and do as much php as possible inside the php file?
Your right it's not nice, instead use proper alternative syntax, for content with a large amount of HTML:
<?php if($foo == $bar): ?>
<div>
<p>hello, world</p>
</div>
<?php endif ?>
I don't believe you need a seperate template language to write maintainable code, PHP is perfectly fine in outputting variables in HTML.
Really the problem is seperating your logic from your output which a template engine can't help with if your not structuring your code properly in the first place. For example stuffing it all in an index.php file or not using MVC whereas you don't put HTML with your logic.
If you have a large project or are overly concerned with separating your PHP from your views, or you want the features which come with a template engine like built in caching and slots etc, then use one. But maybe first look at learning a framework which will improve your overall codebase as most frameworks come with their own. Though essentially you can achieve the same thing including nesting partials and blocks/slots with a 20 line view class which uses ob_* functions, which doesn't require you to learn a new syntax.
Rant over.. :s
Use a templating system like Smarty so you can separate your logic from your display code.It also allows you to bring in a designer that can work with html and might not know php at all. Smarty templates read more like HTML than PHP and that can make a big difference when dealing with a designer.
Ansered by #boatcoder
You can learn here
Without the use of templating engine, your best bet is #Lawrence's answer or this littly modified syntax of your first exemple (trimminig space and php tag) :
<? if($foo == $bar) { ?>
<div>
<p>hello, world</p>
</div>
<? } ?>

PHP: php variable in html link (<a>)

Please help me with this problem.
<?php echo $userRow2['description']; ?>
It seems that the PHP variable is incompatible with html link :(
so I want to know what is the proper method.
TIA...
echo those variables there like the following.
<?php echo $userRow2['description']; ?>
Please use a template engine for these kinds of things...
Use one of:
smarty
twig
mustache
php-view
These will brighten up your day and remove the complexity out of your html files
You can also pass all your GET params in an associative array, and use:
http_build_query($params)
so:
or in your way:
<?php echo $userRow2['description']; ?>
You can also build html/php mix with heredoc:
http://www.hackingwithphp.com/2/6/3/heredoc
it seems that the php variable is incompatible with html link
Well, PHP runs server-side. HTML is client-side. So there's no way for client-side code to interpret PHP variables.
You need to enclose server-side code in <?php ?> tags in order for it to execute on the server (like you already do elsewhere). Otherwise the server just treats it as any other HTML and returns it to the browser. Something like this:
<?php echo $userRow2['description']; ?>
As you can see, that gets a bit messy. But you can put the whole thing in one echo statement:
echo "$userRow2[description]";
Notice how the double-quotes needed to be escaped in that one, but since the whole thing was a double-quoted string the variables contained therein would expand to their values.
There are readability pros and cons either way, so it's up to you how you want to present it.
you should use this
<?php echo $userRow2['description']; ?>
or
<?=$userRow2['description']?>
You can also use Here Doc Syntax
<?php
//test variables
$inst_id = 1;
$description = "Test 1";
$eof = <<<EOF
$description
EOF;
//test output
echo $eof;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

How can I call a php variable inside html like smarty syntax?

I wants to know if someone have an idea of how can we call a variable inside html code like if we are using the smarty template.
<?php
$var = "sometext";
?>
<html>
<body>
<?php echo $var ?>
</body>
</html>
If we are using smarty template we can do like this:
<?php
$var = "sometext";
?>
<html>
<body>
{$var}
</body>
</html>
Is that possible without using smarty templates? Thank you for help!
You can't use Smarty syntax in 'naked' PHP... that's why it's Smarty syntax.
You have three options:
Use PHP's builtin syntax, which is either <?php echo $var; ?> or <?= $var; ?> (there are good reasons not to use the second, mostly that it's difficult to comment out in PHP. You have to use HTML comments which leave remnants of PHP in your HTML source.)
Write your own templating engine which parses your template files, you can use preg_match to search for a pattern like /\{(.*?)\}/ and replace them with the variables, but beware that code replacement causes complexities. If you want to go this route, look into output buffering and regex.
Use Smarty or another templating engine you like. These libraries exist, so take advantage of them.
Note: in PHP 5.4 or newer, even if short tags are disabled, the short echo tag will work. Therefore, as long as you're not running unsupported old versions of PHP, you don't have to worry about access to it.

Getting PHP to write clean html

My PHP tends output html in really long, difficult to read html.
If my PHP is written as:
<?php
echo "<li>";
echo "<strong>Hello</strong>";
echo "</li>";
?>
it outputs HTML like this
<li><strong>Hello</strong></li>
which dosnt look that bad, but imagine if thats within a foreach loop which out putted variants of that, all on one line..
Is there a way to get my PHP to output as neatly composed HTML ?
There is: include the whitespace in your output (for example, add \n after each tag).
However, doing that is really an exercise in futility. If you want to view the HTML yourself, get an HTML pretty printer (or use the one included in your browser's developer tools). If it's meant for a browser, the browser doesn't care.
Use a template engine like SMARTY. This will allow you to keep all your html in completely different files than your PHP (it does compile as PHP). This will improve the readability of all of your code. You can then format the html any way you see fit.
You can use the \n to make a line break.
<?php
echo "<li>\n";
echo "<strong>Hello</strong>\n";
echo "</li>\n";
?>
But why use your time on it? Chrome details console will fix it if its because you use the html source as a debug tool.
Whether this is nice or not is subjective, but it works:
<?php
for ($i = 0; $i < 5; $i++)
{
?>
<li><strong>Hello</strong></li>
<?php
}
?>
What I'm trying to get at here is that you can go in and out of PHP mode, so if you have long strands of HTML, you can format them as such, instead of echoing everything.

Best way to incorporate javascript in php?

This is the way I am currently doing it.
<?php
//show footer
echo "<script type='text/javascript'>\n";
echo "alert('Congrats');\n";
echo "</script>";
?>
Is there a better way than just to echo it?
Just put your JavaScript code outside PHP tags:
<?php
// your PHP code goes here
?>
// your javascript function out of the PHP tag.
function f() {
alert('congrats');
}
of course
?>
alert('Congrats');
<?
If you really have to execute the js by printing it from the PHP, it would at least be cleaner if you had your js functionality stored in functions in some file and then called them by printing the calls.
I recommend reserving PHP files just for PHP code and keeping your frontend code (HTML/CSS/javascript) in separate template files.
Last time I checked, mixing the presentation layer & backend code into same file was popular about 12 years ago.
Your file hierarchy for a project could look like this:
- my_project
- lib
- PHP files here
- templates
- HTML templates here
- public <- this is your document root for web server
- index.php <- just a dispatcher
- js
- images
- css
Use HEREDOCS, or break out of PHP mode into "html" mode. If the Javascript is entirely static, or has a few parts that need to have some PHP value included, drop into html mode ('?>' out of php). This will allow any decent text editor to realize that you're doing HTML and Javascript, and syntax highlight as appropriate. The following are all equivalent, but decide for yourself which is more readable:
'pure php':
<?php
echo '<script>';
echo ' var x = [' . $somePHPvar . '];';
echo ' alert(x);';
echo '<script>';
?>
'heredoc' syntax:
<?php
echo <<<EOF
<script>
var x = [{$somePHPvar}];
alert(x);
</script>
EOF;
?>
'html mode':
<?php ?>
<script>
var x = [<?php echo $somePHPVar ?>];
alert(x);
</script>
plusses/minuses for each:
pure php: you can stay in PHP mode, and your echo + $vars will be highlighted as PHP code, but the html/javascript you're echoing will be treated as plain text and colored as such (ie: all the same color)
heredoc syntax: You stay in PHP mode, but gain the benefit of not having to escape any quotes (' and ") in your code, so any html will look cleaner. Most editors will recognize PHP vars in the heredoc block and color them appropriately, but the rest of the text will be treated as text, so javascript/html look the same. Also, you cannot insert function calls into the text. You have to do those BEFORE starting the heredoc and store the results in a var, which can be inserted. The HEREDOC can also be use to assign long text blocks into a variable directly.
'html mode': The editor will see/recognize your html, javascript, AND php and color them appropriately. But this is at the cost of having to sprinkle php open/close tags anywhere you need to fill in some value dynamically. On the plus side, you can directly insert function call results (htmlspecialchars(), urlecncode(), html_strip_tags(), etc...) without having to store the values in an intermediate var. It also makes for harder-to-maintain code as your PHP is now sprinkled randomly throughough the html/javascript code.
It all boils down to what's easiest for the particular code you're working on.
You can use the model-view-controller pattern for outputting JavaScript.
You can have a "view" file where most of your JS is stored:
myJavascript.js.php:
alert('hello bob');
alert('hello <?php echo $name; ?>');
alert('whats up?');
Your controller, jsController.php:
$name = "Jane";

Categories