0

我对 PHP 很陌生,我只是在玩 PHP,

我通过ajax post从表单获取数据到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);
?>
4

2 回答 2

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);
?>
于 2013-03-08T06:52:31.830 回答
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!

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

于 2013-03-08T07:04:07.113 回答