Php 按顺序将数据写入文本文件
我对PHP非常陌生,我只是在玩PHP 我通过ajax post到php从表单中获取数据,数据被添加到文本文件中,我想将这些数据按顺序排列 像 现在它像这样被添加,没有任何数字Php 按顺序将数据写入文本文件,php,ajax,post,Php,Ajax,Post,我对PHP非常陌生,我只是在玩PHP 我通过ajax post到php从表单中获取数据,数据被添加到文本文件中,我想将这些数据按顺序排列 像 现在它像这样被添加,没有任何数字 username , emailid , etc username , emailid , etc 下面是我的PHP代码 <?php //print_r($_POST); $myFile = "feedback.txt"; $fh = fopen($myFile, 'a') or
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);
?>
试试这个:
<?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);
?>
这允许您添加新条目,并根据“自然”顺序对所有条目进行排序;i、 e.人类最有可能将元素放入的顺序:
→ 第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!
让我知道它是如何工作的。您的代码缺少该号码。是什么阻止您添加它?在哪里?如何添加数字?请检查打印($matches['digit'])代码>看看接下来会发生什么它只是打印数组()哦,我很抱歉,它是preg\u match\u all('/(?P\d*)\)\s/,$content,$matches)
我写了$filename
而不是$content
。我编辑了代码请现在检查
# 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!