Output buffering and calling ECHO on an HTML string also containing ECHO - php

I have a template file that contains html with inlined PHP echo statements. For example, the template may look like:
<div class="<?php echo $classes ?>">
<div class="uk-container uk-container-center">
<section class="uk-grid uk-grid-match" data-uk-grid-match="{target:'> div > .uk-panel'}" data-uk-grid-margin>
<?php echo $content ?>
</section>
</div>
</div>
The template is read in the script using file_get_contents(). I then turn on output buffering. The variables $classes and $content are in scope at the time ob_start() is called.
ob_start();
echo $htmlTemplateString;
$resolvedMarkup = ob_get_clean();
Unfortunately, $resolvedMarkup contains the original string read from the template file and the inlined echo statements are still present and not resolved to the values of the referenced variables.
My question is, am I interpreting this usage correctly? Should I be getting back a fully resolved string?
Normally, I could use include to achieve this sort of thing but on this occasion, despite the brevity of the example code, there are numerous reasons why the templates are brought into memory (mostly because each template may be in a hierarchy of templates that need to be resolved into each other, altering the original template structure).
At this stage, I am trying to avoid using temporary files.
I hope this question is clear and would appreciate any advice/thoughts as to whether my approach should work and if so, what I might be doing wrong.

Here's your problem:
The template is read in the script using file_get_contents().
file_get_contents() is pretty much the equivalent of fopen(); fread(); fclose(). It simply sucks bytes from a file into a variable. Those bytes are NOT executed, so any PHP code blocks which maybe in that file remain as <, ?, p, etc... characters - they're not executed/replaced.
You need to use include() instead. That will execute any PHP code in the byte stream.

Just echo does not actually parse any PHP. What you need is eval.
Here I have to convert my template into text that can be parsed by php.
<?php
$str1 = " this is <?php echo \$i;?> now\n";
$i=99;
echo eval('?>' . $str1 . '<?php ');

Related

PHP output in HTML file

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

HTML string to PHP variable without loosing IDE syntax highlighting

I want to add a very large HTML string to a PHP variable. When i do something like $html = "<div>info</div>"; the string will go gray and the normal highlighting no longer works. I want to use some PHP to build the HTML, but most of it will be coded directly into the file. I can't echo the HTML it needs to be in a variable as it gets passed to a function.
Is there another way other than $html = ""; to assign data to a variable that will allow me to keep syntax highlighting. My thoughts would be some sort of syntax that will allow me to close the PHP tag, but won't output the content, but rather saves that output to a variable.
?$html>
<div>content</div>
<?php
I understand this is impossible as the server will not read any lines outside of the PHP tags, but it's just an example to get across what I'm trying to do.
Edit
I have also thought of using
$html = file_get_contents(site.com/file.php);
This would be wasteful as it creates another HTTP request to a PHP page. the page needs to be PHP in order to dynamically build some of the HTML
You can use output buffering with ob_start and ob_get_clean for that:
<?php
ob_start();
?>
<html>
... all your html comes here
</html>
<?php
$html = ob_get_clean();
?>
At the end of the above code, nothing will have been output to the browser, but your $html variable will have the content.

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

Print <<< END; question

Okay, so I have a question. I use print <<< END followed by an END; after my html and variables instead of echo and print. I use this because it doesn't seem to have an effect on speed and the code just looks more organized in my opinion. I'm sure others will disagree but it's just my opinion.
I have a current project and that's the primary method I use to output HTML. No problems so far.
What are the disadvantages to using this? I have spoken with coders about it before, but they never really give me a reason not to use it just to not use it. I would appreciate any advice on this because I haven't had any problems with it.
The syntax you're describing is called a heredoc. As far as I know there is no performance difference between using heredocs and single- / double-quoted strings.
Heredocs can often help to prevent syntax errors, because there is no need to escape ' and " within the string. Another option would be to jump out of PHP into plain HTML, which requires no echo calls whatsoever:
<?php
... do things ...
?>
<div id="result"><?php var_dump($result); ?></div>
<?php
... do more things ...
?>
The only disadvantage i can think of is its harder to read for developers. This too is opinion but i find it much easier to read alternate syntax in template files, i.e.:
<?php if($something): ?>
<div id="something">
<?php echo $something->text ?>
</div>
<?php endif; ?>
And switching in and out like this is the only reason i can see to use heredoc as far as html is concerned. IF you have functions that are outputting massive amounts of html then you should change those to include a file in some manner. IE. you shoudl need to switch in and out of html except in your view, and those views should be separate completely form your functions or models. for exampl you should be doing:
function getSomething($var){
if($var){
$html = <<< HTML
<div id="something">
$var->text
</div>
HTML;
}
}
This is obvioulsy a simle example and actually this example isnt so bad, but if the HTML is more complex it starts to get jsut ugly. And in the case of methods on model classes its just plain evil no matter how simple the HTML is. Id prefer something like the following:
getSomething($var, $template = 'something.php')
{
if($var){
ob_start();
include($template); // $var is accessible in something.php
return ob_get_clean();
}
return null;
}
Of course the include will result in slight a performance hit but thats where caching comes in :-)

Including dynamic HTML with PHP

I have PHP variables to place within an included HTML file. What's the best way of executing this?
//contents of file1.php
$variable1 = "text 1";
$variable2 = "text 2"
$newContent = include('file2.php');
echo $newContent;
//contents of file2.php
<p>standard HTML with PHP... <strong><?=$variable1?></strong></p>
<p><?=$variable2?></p>
This general method is considered OK but the actual code here doesn't work. Do I use file_get_contents() or include(), how do I execute the PHP within the includes file to output the correct contents?
Should I be using something like HTML>>>
What you're doing is fine, and you'll find that most people use the same exact method. I personally wouldn't use PHP short tags (some hosts don't enable it), but that's a matter of preference.
Edit: As per your edit, it seems like you don't have short tags enabled. Check your ini (http://php.net/manual/en/ini.core.php). But you really shouldn't be using short tags, because as clownbaby mentions, PHP 6 will deprecate them. Even if you don't care about future proofing your code, they're still troublesome (which is evident because your code isn't working). Switch to <?php echo $variable1; ?> and you'll be fine.
I think your code is fine, even most frameworks use it...
regarding the use of short tags, some servers do not allow it, so here is a workaround I use:
if ((bool) #ini_get('short_open_tag') === FALSE){
echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents("path/to/file2.php"))));
}else{
$newContent = include("path/to/file2.php");
echo $newContent;
}
$newContent = include('file2.php');
echo $newContent;
You shouldn't need to echo anything here. Just including the PHP file should execute any code inside it and spit out the interpolated template to the page. Whilst there is such a thing as returning a value from include, it's a rarely used feature you can generally ignore.
As ekhaled said, you may need to enable short tags or replace them with the always-supported <?php ... ?> processing-instruction-style syntax.
However, it's important to htmlspecialchars every text string when including it in HTML, or you've got a potential XSS security hole.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
?>
...
<p>standard HTML with PHP... <strong><?php h($variable1) ?></strong></p>
<p><?php h($variable2) ?></p>

Categories