include html code inside php with determine variable - php

I have a PHP code which sends an email with HTML template.
HTML template has some PHP variable like Name, Email, etc.
<strong>Name: {name} </strong>
because email template has more code, I include it in my PHP file
$htmlInvoice = file_get_contents($_SERVER["DOCUMENT_ROOT"] .'/mail/invoice.html');
$name= $user['name']);
$msg = $htmlInvoice;
But when an email sent, it can not read variables inside the
HTML file. and for example echo $name like a text

You can use strtr for this. For e.g:
<?php
$a = 'Hi this is {name}. I am writing {language}';
echo strtr($a, ['{name}' => 'Abhishek', '{language}' => 'php']);
Strtr

You need to replace the {name} string for your desired output.
$htmlInvoice = file_get_contents($_SERVER["DOCUMENT_ROOT"] .'/mail/invoice.html');
$name= $user['name']);
$msg = str_replace('{name}',$name, $htmlInvoice);

You could change /mail/invoice.html to include PHP commands.
<strong><? echo $user['name'] ?></strong>
Then
$htmlInvoice = file_get_contents($_SERVER["DOCUMENT_ROOT"] .'/mail/invoice.html');
$msg = _readphp_eval($htmlInvoice);
function _readphp_eval($code) {
ob_start();
print eval('?>'. $code);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
I don't know who to attribute _readphp_eval($code) function to ... It is floating around the internet, and works very nicely for this purpose.
It would require that $user['name'] be defined/included in the invoice.html file.

Related

php call variable and put back on while loop

sorry for my last question where i try put some live code with ob_start buffer content is not helping me to solve my problem because buffer content just collects output text, it doesn't execute any code. thanks #akrys for your advices
what i want is to put code into while looping like this
$sql = $conn->query("SELECT * FROM `users`");
$var = $row['full_name'];
include('test.php');
after i call test.php contain while code like:
while($row = $sql->fetch_array()) {
echo $var;
}
everything is work if i replace $var with $row['full_name'];
but i get the name of row field from some script on index.php so i should access that file first then i call portable file contain query to fetch_array on test.php
how to make it work when i put it back with $var contain variable field name
thank you very much for your attention guys
you should to include before your code
page
test.php
<?php
$someVariable = 'hello'; // the variable only can access in here
?>
<?php
include('test.php');
ob_start();
echo "some text with call variable $someVariable";
echo "other stuff";
$tdcol1_val = ob_get_contents(); ob_clean();
echo $tdcol1_val; //
?>
of course you can use define too
page test.php
<?php
define( "SOMEVARIABLE", hello );
?>
<?php
include('test.php');
ob_start();
echo "some text with call variable ".SOMEVARIABLE;
echo "other stuff";
$tdcol1_val = ob_get_contents(); ob_clean();
echo $tdcol1_val; //
?>
you can use:
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
for more help, use the link below:
enter link description here

How to capture HTML for a PHP variable

I have dozens of templates elaborated by a web designer. They are primarily HTML, with a few PHP tags and data. The problem is that I need to re-use those templates (tpl.php) to send email, and the email body (through PHPMailer) is a variable. I have succeeded to fill a variable with the HTML output in the code example (adapted). My question is: should I redo all the templates or is this a valid approach?
<?php
print "This will print just the 'hello world' output. I don't need to print the function as it has no return value<br />";
hola_mundo(); // I directly call the function and it outputs HTML to the screen
print "<br />";
// Now the assignment to the variable.
ob_start(); // I silence the output to screen
hola_mundo();
$string = ob_get_contents(); // I capture the buffer
ob_end_clean(); // I restore the output to screen
print "Now I print the string variable to demonstrate it has captured the HTML ";
print $string;
function hola_mundo(){
?><font color="red"<b>HOLA MUNDO CRUEL</b></font><?php
} // function
?>
The more logical approach would be to have this function (which I do not have and should redo for dozens of templates):
<?php
$string = hola_mundo();
print $string;
function hola_mundo(){
$string = '<font color="red"<b>HOLA MUNDO CRUEL</b></font>';
return $string
} // function
?>
Do you mean this?
function getTemplate($file) {
ob_start();
include $file;
return ob_get_clean();
}
// Example usage:
$string = getTemplate('templates/tpl.php');
tpl.php will be executed as a PHP file.
You can even pass variables to the template:
function getTemplate($file, $variables=array()) {
extract($variables);
ob_start();
include $file;
return ob_get_clean();
}
// Example usage:
$string = getTemplate('templates/tpl.php', array('message' => 'Hello world!'));
This will extract 'Hello world' into the function scope, making it available as the $message variable to the template.

import content of php file into a php variable

I have an external php file like this:
<!DOCTYPE>
<head>...
...
<body>
<p><?php echo $content;?></p>
..
AND in my code:
$content = 'sample text';
$body = include("layout/mailtemplate.php");
You can see it has php and html code (and pass $content outside of file to included file)
Is there any way to store content of this file to a php variable?
(here content of $body is "1"!)
Also I test
$body = file_get_contents('layout/mailtemplate.php');
It works, but I could not pass $content to file.
(I know I could pass it via GET) but I have a lot of variables. Is there a simpler way?
Yes, you can. You need to use output buffering for that:
ob_start();
$content = 'sample text';
include("inc.php");
$body = ob_get_contents();
ob_end_clean();
var_dump($body); // string(11) "sample text"

PHP include HTML and echo out variable

I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.
You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.
If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}
All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>
If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);
It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;

Get code between php tags with regular expression

I'm trying to get php code out of a HTML template file to execute it and place the result back.
What regular expression code can I use? And is there a method that also return the position of the found first tag?
<p>some html</p>
<?php $some = "php code"; ?>
<p>some <em>more</em> html</p>
<?php $some = "more php code"; ?>
I want the php code filtered from the html.
preg_match("/<\?.*?\?>/m",$output,$matches)
or
preg_match("/<\?.*?\?>/s",$output,$matches)
Should match all lines.
Instead of "getting the PHP out and putting it back" you should pass the variables to the template file.
Something like this:
<?php
function loadTemplate($path,$data=array()){
if (file_exists($path) === false){
throw new Exception('Template not found:'.$path);
return false;
}
extract($data);
ob_start();
require($path);
$return = ob_get_contents();
ob_end_clean();
return $return;
}
$vars = array('var1'=>$value,
'var2'=>$somevalue,
'var3'=>$someothervalue,
'var4'=>$blab);
$template = loadTemplate('path/to/thefile.php',$vars);
?>
Then access the $vars array values from within thefile.php like
echo $var1
echo $var2
ect
Hope it helps

Categories