需要帮助 - php save .txt

时间:2014-02-19 09:38:18

标签: php

我需要你的帮助。 我需要每次代码将信息存储在txt文件中,然后每个新记录到新行以及应该对所有文件进行编号?

<?php
$txt = "data.txt"; 
if (isset($_POST['Password'])) { // check if both fields are set
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['Password']; 
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
}
?>

<?php $txt = "data.txt"; if (isset($_POST['Password'])) { // check if both fields are set $fh = fopen($txt, 'a'); $txt=$_POST['Password']; fwrite($fh,$txt); // Write information to the file fclose($fh); // Close the file } ?>

3 个答案:

答案 0 :(得分:1)

添加了一些注释来解释这些更改。

<?php
$file = "data.txt";  // check if both fields are set
$fh = fopen($file, 'a+'); //open the file for reading, writing and put the pointer at the end of file.  

$word=md5(rand(1,10)); //random word generator for testing
fwrite($fh,$word."\n"); // Write information to the file add a new line to the end of the word.

rewind($fh); //return the pointer to the start of the text file.
$lines = explode("\n",trim(fread($fh, filesize($file)))); // create an array of lines.

foreach($lines as $key=>$line){ // iterate over each line.
    echo $key." : ".$line."<br>";
}
fclose($fh); // Close the file
?>

PHP

fopen

fread

explode

答案 1 :(得分:0)

你可以用更简单的方式做到这一点..

<?php
$txt = "data.txt"; 
if (isset($_POST['Password']) && file_exists($txt))
    { 
      file_put_contents($txt,$_POST['Password'],FILE_APPEND);
    }
?>

答案 2 :(得分:0)

我们打开要写入的文件,你必须像 php doc 那样处理a+ 所以你的代码将是:

<?php
$fileName = "data.txt";  // change variable name to file name
if (isset($_POST['Password'])) { // check if both fields are set
    $file = fopen($fileName, 'a+'); // set handler to a+   
    $txt=$_POST['Password']; 
    fwrite($file,$txt); // Write information to the file
    fclose($file); // Close the file
}
?>