0

AM very new to PHP , I am just playing with PHP ,

Am getting data from form via ajax post to php , the data getting added to text file , I want to place that data in order

like

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

now its getting added like this without any numbers

  username , emailid , etc  
  username , emailid , etc

below is my PHP code

<?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 ファイルを 1 行ずつ読み込む

# 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 に答える