0

I am trying to replace values of variable

I have following file

demo.html

<h1>{$heading}</h1>
<p>{$paragraph}</p>

demo.php

    $html = file_get_contents('email.html', true);
    eval($html);

here I am trying to include that file and replace values of $heading and $paragraph and than echo.

my question is how to do that?

3 Answers 3

1

First off, eval() is not needed for this code, as it contains no PHP which needs to be executed. eval() is a very dangerous function. You contents is in $html as a string, therefore, you can now use a significantly safer function called str_replace() to look for, and replace the value placeholders with the correct data.

The function uses the following arguments: str_replace($search, $replace, $subject), accepts arrays as arguments, and returns the full string with replaced values.

Therefore, to answer your question:

// $html = ...

$search = array(
    '{$heading}',
    '{$paragraph}'
);
$replace = array(
    'My Heading',
    'My Paragraph',
);

$replaced_string = str_replace($search, $replace, $html)
Sign up to request clarification or add additional context in comments.

2 Comments

very dangerous because it sounds like evil ? And the variables in the code can be evaluated if its done right ;) But like goto everybody avoid to use it. PHP is dangerous at all if you are not using it with save coded conditions.
Absolutely. For a trivial task however, using eval is dangerous because it opens up exploits that an inexperienced developer might not know about. While it could be eval()'d, there is an alternative option which does the same thing, and is a lot safer :)
0

Use str_replace.

$replace = array(
  '{$heading}'   => 'Replaced heading',
  '{$paragraph}' => 'Replaced paragraph'
);

$html = file_get_contents('email.html', true);
$html = str_reaplce(array_keys($replace), array_values($replace), $html);
echo $html;

Comments

0

Change demo.html to demo.tpl.php

In demo.php just do:

 $heading = 'Heading';
 $paragraph = 'Para';
 include 'demo.tpl.php';

That should work.

OR if no name change is possible, in demo.php do:

$heading = 'Heading';
$paragraph = 'Para';
print str_replace(
          array('{$heading}','{$paragraph}'), # use '  not " here!!!
          array($heading,$paragraph),
          file_get_contents('demo.html'));

Should work too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.