繁体   English   中英

PHP代码可编辑文本文件的不同行

[英]PHP code to edit different lines of a text file

我有以下格式的文本文件,我们称它为stats.txt:

valueA1, valueA2, valueA3, valueA4
valueB1, valueB2, valueB3, valueB4
valueC1, valueC2, valueC3, valueC4
valueD1, valueD2, valueD3, valueD4

我希望在HTML文档中用此代码填充四个文本框或文本区域,并在提交表单时将其追加到文本文件的相应行中。 我对php不太了解,所以找不到解决方法。

我当前的html文件如下所示:

$url = 'editor.php';
$file = 'stats.txt';

// check if form has been submitted
if (isset($_POST['text1']))
{
    // save the text contents
    file_put_contents($file, $_POST['text1']);

    // redirect to form again
    header(sprintf('Location: %s', $url));
    printf('<a href="%s">Updated</a>.', htmlspecialchars($url));
    exit();
}

// read the textfile
$text = file_get_contents($file);

?>

我无法弄清楚如何在文本文件的各行之间循环,因此请使用这段可怕的代码来获取每一行的值:

    <?php
    //for Line 1
    $myLine1 = 1 ; 
    $linefile1 = new SplFileObject($file);
    $linefile1->seek($myLine1-1);

    //for Line 2
    $myLine2 = 2 ; 
    $linefile2 = new SplFileObject($file);
    $linefile2->seek($myLine2-1);

    //for Line 3
    $myLine3 = 3 ; 
    $linefile3 = new SplFileObject($file);
    $linefile3->seek($myLine3-1);

    //for Line 4
    $myLine4 = 4 ; 
    $linefile4 = new SplFileObject($file);
    $linefile4->seek($myLine4-1);
    ?>

表单如下所示:

<form action="" method="post">
#stuff 1
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile1) ?></textarea>
#stuff 2
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile2) ?></textarea>
#stuff 3
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile3) ?></textarea>
#stuff 4
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile4) ?></textarea>
<input type="submit" />
<input type="reset" />
</form>

有人可以帮我吗?

这是我编写的用于存储和检索文本文件中数据的代码,您可以用作示例:

// Save Check Boxes in Serial Form for later retrieval
$myFile = "equipment.txt";
if($save == "yes"){
$stringData = serialize(array($container_20,$container_40,$container_45,$container_RF,$container_HQ,$container_Chassis));
file_put_contents($myFile, $stringData);
}

// Read Saved File and Populate Check Boxes
$recoveredData = file_get_contents($myFile);
list($container_20,$container_40,$container_45,$container_RF,$container_HQ,$container_Chassis) = unserialize($recoveredData);

只需循环浏览并显示文本区域。 使用file()将文件放入数组

 <?php $file = file('stats.txt');?>

  <form action="" method="post">
     <?php
     foreach($file as $line) {
        echo "<textarea id='stuff' name='stuff[]'>".htmlspecialchars($line)."</textarea>";
     };?>
    <input type="submit" />
    <input type="reset" />
</form>

然后,当您提交表格

    if(isset($_POST['stuff'])){
        $text = join("\n", $_POST['stuff']);
        file_put_contents($file, $text);
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM