按顺序将数据写入文本文件

时间:2013-03-08 06:29:39

标签: php ajax post

AM非常新的PHP,我只是在玩PHP,

从表单通过ajax帖子获取数据到php,数据被添加到文本文件中,我想按顺序放置数据

 1) username , emailid , etc  
 2) username , emailid , etc

现在它的添加没有任何数字

  username , emailid , etc  
  username , emailid , etc

下面是我的PHP代码

<?php
    //print_r($_POST);
    $myFile = "feedback.txt";
    $fh = fopen($myFile, 'a') or die("can't open file");
    $comma_delmited_list = implode(",", $_POST) . "\n";
    fwrite($fh, $comma_delmited_list);
    fclose($fh);
?>

2 个答案:

答案 0 :(得分:1)

试试这个:

<?php

    //print_r($_POST);
    $myFile = "feedback.txt";

    $content  = file_get_contents($myFile);
    preg_match_all('/(?P<digit>\d*)\)\s/', $content, $matches);
    if(empty($matches['digit'])){
      $cnt  = 1;
    }
    else{
      $cnt  = end($matches['digit']) + 1;
    }

    $fh = fopen($myFile, 'a') or die("can't open file");
    $comma_delmited_list = $cnt.") ".implode(",", $_POST) . "\n";
    fwrite($fh, $comma_delmited_list);
    fclose($fh);
?>

答案 1 :(得分:0)

这允许您添加新条目并根据“自然”顺序对所有条目进行排序;即人类最有可能将这些元素放入的顺序:

第1部分:逐行读取.txt文件

# variables:
    $myFile = "feedback.txt";
    $contents = array(); # array to hold sorted list

# 'a+' makes sure if the file does not exists, it is created:
    $fh = fopen( $myFile, 'a+' ) or die( "can't open file" ); 

# while not at the end of the file:
    while ( !feof( $fh ) ) { 

        $line = fgets( $fh ); # read in a line

        # if the line is not empty, add it to the $contents array:
        if( $line != "" ) { $contents[] = $line; } 

    } 
    fclose($fh); # close the file handle

第2部分:添加新条目和“自然”排序列表

# add new line to $contents array
    $contents[] = implode( ",", $_POST );

# orders strings alphanumerically in the way a human being would
    natsort( $contents ); 

第3部分:将已排序的行写入.txt文件

# open txt file for writing:
    $fh = fopen( $myFile, 'w' ) or die( "can't open file" ); 

# traverse the $contents array:
    foreach( $contents as $content ) { 

         fwrite( $fh, $content . "\n" ); # write the next line 

    }
    fclose($fh); # close the file handle

# done! check the .txt file to see if it has been sorted/added to!

让我知道它是如何运作的。