Php 如何用fwrite()中的值替换文件_get_contents()中的变量?

Php 如何用fwrite()中的值替换文件_get_contents()中的变量?,php,forms,file-get-contents,fwrite,Php,Forms,File Get Contents,Fwrite,我有一个大的表单,用户写的所有数据都以一种特殊的方式处理。提交后的表单应该加载模板php文件,并将表单中的数据添加到其中。因此,我的应用程序处理POST数据,通过file\u get\u contents()加载php模板,并通过fwrite()将数据写入新的php文件 但问题来了。php模板文件中的变量按原样编写。但我需要将php模板中的变量替换为来自提交和解析表单POST头的值 有人知道怎么做吗 我的简化代码: -- form.php <Form Action="process.php

我有一个大的表单,用户写的所有数据都以一种特殊的方式处理。提交后的表单应该加载模板php文件,并将表单中的数据添加到其中。因此,我的应用程序处理POST数据,通过
file\u get\u contents()
加载php模板,并通过
fwrite()
将数据写入新的php文件

但问题来了。php模板文件中的变量按原样编写。但我需要将php模板中的变量替换为来自提交和解析表单POST头的值

有人知道怎么做吗

我的简化代码:

-- form.php
<Form Action="process.php" Method="post">
<Input Name="Name1" Type="text" Value="Value1">
<Button Type="submit">Submit</Button>

-- process.php
$Array=array(
"Name1","Name2",//...
);
if(!empty($_POST)){
foreach($Array as $Value){
if(!empty($_POST[$Value])){
$Value=$_POST[$Value];
}}}
...
$Template=file_get_contents("template.php");
$File=fopen("../export/".$userid.".html","w+");
fwrite($File,$Template);
fclose($File);

-- template.php
<!Doctype Html>
...
Name1: <?=$Name1?><Br>
...
--form.php
提交
--process.php
$Array=Array(
“名称1”、“名称2”和/。。。
);
如果(!空($\u POST)){
foreach($Array作为$Value){
如果(!空($\u POST[$Value])){
$Value=$_POST[$Value];
}}}
...
$Template=file_get_contents(“Template.php”);
$File=fopen(“../export/”$userid。“.html”,“w+”);
fwrite($File$Template);
fclose($文件);
--template.php
...
名称1:
...
我的目标是:

-- 135462.html
<!Doctype Html>
...
Name1: Value1
...
--135462.html
...
名称1:Value1
...

我想您正在寻找php缓冲区。 ob将帮助你做到这一点

检查

template.php:

<html>
<head></head>
<body><?=$foo?></body>
</html>

index.php:

<?php
$foo = $_POST['text'];
ob_start();
include('template.php');
$template_html = ob_get_contents();
ob_end_clean();

//do your stuff

echo $template_html;
?>


fwrite()
不会解析您的PHP,因此所有代码都像纯文本一样。如果模板是PHP文件,为什么不将其包含在
中?@barell是的,我没有意识到这一点(我想,我会这样做)。但是有什么更简单、更直接的吗?@Niloct因为模板包含很多HTMLWhat?模板确实有HTML和混合的
代码。如果
包含“template.phtml”
(例如),模板可以立即使用前面的所有变量。@AlesKvapil如果确实需要写入文件,请将此答案的最后一行改为
fwrite($newfile,$template\u html)
。谢谢你们,我将尝试itfwrite()或file\u put\u contents(),我使用fwrite()然后使用mail()。我试过了,效果很好!谢谢大家。