dongmieqiao3152 2018-09-08 15:39
浏览 189

使用PHP替换文本文档中的特定字符串

I'm trying to make the user input form data and when hitting submit it places the form data in a existing text file and replaces the specific string with that form data.

<?php
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fName = $_POST["fName"];
fwrite($fh, $fName);
$mInitial = $_POST["mInitial"];
fwrite($fh, $mInitial);
$lName = $_POST["lName"];
fwrite($fh, $lName);
$placeholders = array('fin', 'min', 'lana');

$namevals = array($fName,$mInitial,$lName);

echo "<br/>namevals 0:".$namevals[0];

$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);

//build the string by putting each piece of text and variable exactly where 
you want it:
$string = "I, ".$fName." ".$mInitial." ".$lName.", a resident of Neverland 
County, Virginia, revoke any prior wills and amendments to wills made by me 
and declare this Will to be my Last Will and Testament.";

file_put_contents($path_to_file,$string);
fclose($fh);
?> 

This is something that I have already but all it does it build the string from the code and not actually inserting it into the file but rewriting the whole line. I need to go to another page when the user hits submit so the data needs to pass over and not replace what is already done but keep adding to it.

<h2>Please enter your name.</h2>
<form method="post" action="<?php echo 
htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
First Name: <input type="text" name="fName">
<br><br>
Middle Initial: <input type="text" name="mInitial">
<br><br>
Last Name: <input type="text" name="lName">
<br><br>
<input type="submit" name="submit" value="Next"> 
<button type="button" onclick="location.href='download.php'">Download 
will</button>  
</form>

Here is my form data

  • 写回答

1条回答 默认 最新

  • dsh8009271 2018-09-08 17:43
    关注

    Change the code as following:

    $file_contents = str_replace($placeholders,$namevals,$file_contents);
    
    // removed $string
    
    file_put_contents($path_to_file,$file_contents);
    fclose($fh);
    

    The issue was you were writing $string to file instead of writing the $file_contents which was extracted from the file.

    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛