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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献