2013-03-08 2 views
0

очень новой для PHP, я просто играл с PHP,Запись данных в текстовый файл с целью

Am получать данные из формы через 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); 
?> 
+0

В вашем коде отсутствует номер. Что мешает вам добавить его? – hakre

+0

где? как добавить номера? – EnterJQ

ответ

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); 
?> 
+0

Номер не получает прирост .... продолжайте добавлять только 1 – EnterJQ

+0

Пожалуйста, проверьте 'print_r ($ matches ['digit']);' и посмотрите, что там происходит –

+0

его просто печатают Array() – EnterJQ

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! 

Сообщите мне, как это работает.

Смежные вопросы