3

In PHP I have the need to generate HTML pages from a template and insert variables in specific places then save them to disk.

So far this code works well:

<?php 

$client = "John doe";

$template = "

<html>
<body>
<div>
$client
</div>
</body>
</html>

";

$htmlCode = $template;

$fh = fopen("page.html", 'w') or die("can't open file");
fwrite($fh, $htmlCode);
fclose($fh);

?>

ultimately I want to slurp and read in the $template from a file on disk, using something like:

$template = file_get_contents("template.html");

But using this approach I can not get the $client replaced with the "John doe" instead it shows as $client in the HTML code when I save it to disk.

I did read some posts about using regex and printf to replace substings, but i could not see how can I use them in my scenario. I am positive there must be easier and better way.

There will be a need of a lot of variables plopped in many places so I do not want to create a regex for each one. I just want to be able to stick a $variable anywhere in the external html file and PHP should replace it with a variable content (if it exist). Unfortunately file_get_contents() only slurps it into a string exactly as it is without any interpretations. I was wandering if there is another function that I can use for slurping that will actually work as I indented.

Any suggestions are greatly appreciated.

2
  • 3
    Didn't you read about str_replace() ? Commented Jun 22, 2012 at 19:50
  • 1
    I dont understand your question Commented Jun 22, 2012 at 19:51

8 Answers 8

6

This is very similar to some example code in http://php.net/manual/en/function.ob-start.php and could be useful in your case:

<?php 
function save_callback($buffer) {
    // save buffer to disk
    $fh = fopen("page.html", 'w') or die("can't open file");
    fwrite($fh, $buffer);
    fclose($fh);
    return $buffer; // use it or ignore it
}
$client = "John doe";
ob_start("save_callback");
include("template.php");
ob_end_clean();
?>
Sign up to request clarification or add additional context in comments.

Comments

4

I have done the same thing with reading template files. My template looks like this:

<html>
<body>
<div>{client}</div>
</body>
</html>

Then the PHP code will replace "{client}" with $client.

$template = file_get_contents("template.html");
$contents = str_replace("{client}", $client, $template);

Use whatever delimiter you want n the template: %client% [client] ?client? #client#

Comments

1

In this case I just matched purely alphanumeric variable names.

echo preg_replace_callback("/[$][a-zA-Z0-9]+/", function($varname) {
    return $GLOBALS[substr($varname[0], 1)];
}, $input);

1 Comment

I dislike this because of the use of $GLOBALS
1

It is easy, just write the following:

$html = file_get_contents('0.txt');
// or user is:
$html = '&lt;html&gt;&lt;body&gt;$DATA&lt;/body&gt;&lt;/html&gt;'; 
// remember us single quotation (') not double quotation (&quot;) for a string
$DATA = &quot;&lt;h1&gt;Hi&lt;/h1&gt;&quot;;
eval(&quot;\$html = \&quot;$html\&quot;;&quot;);
echo $html;

Comments

0

You can use a simple regex:

$out = preg_replace_callback("/\$([^\s]+)/",
    function($m) {
        if( isset($GLOBALS[$m[1]]))
            return $GLOBALS[$m[1]];
        else return $m[0];
    },
    $in);

It's not perfect, because it's a very naïve regex, but in most cases it'll do what you want.

Personally, for templating, I'd use something like {%keyword}, that's more easily delimited.

Comments

0

If possible, I would use cURL instead. Just like using AJAX in Javascript, you can request a php page with POST variable in cURL.

In your case, you can create something like this...

// Variables
$client = "John doe";
$your_template_url = "http://UseYourURL.com";


// cURL
$ch = curl_init($your_template_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, ["client" => $client ]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$htmlCode = curl_exec($ch);    
curl_close($ch);


// Write into the file
$fh = fopen("page.html", 'w') or die("can't open file");
fwrite($fh, $htmlCode);
fclose($fh);

In your template, you should have something like...

<html>
   <body>
      <div>
         <?php echo $_POST['client']; ?>
      </div>
   </body>
</html>

Make sure your template is php file, not html. Even you want the html code, you still need php to echo your variable into the html file.

Comments

-1

On php when you are mixing strings and variables if you are using Single quotes:

   $name = "john";
   echo 'The Name is $name';
   // will output: The Name is $name

But if you use double quotes :

    echo "The Name is $name";
    // will output: The Name is john

Comments

-3

I believe this happens because you are writting the variable inside double quotes. Everything inside double quotes will be converted literally into string jus the way they are written in the code.

In the example of yousrs, to get the result you want, when you declare the $template variable, you should should concatenated it with the value you want to add to it, like in the following:

$template = "
<html>
<body>
<div>" . $client . "</div>
</body>
</html>
";

Dots concatenate strings in PHP.

That should do the trick! :)

2 Comments

That is not what OP asked. When the string is created by file_get_contents, the text $client isn't evaluated as a variable and replaced like "you would expect".
Ow, you're right Alex. I think i may have read only the first half of the post. Sorry for that. Anyway, now that i got it, i think the solution'd be to use str_replace(), but I see that was said already! =)

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.