如何使用php将输入值写入文件


How to write input values to a file with php

所以我目前的工作正在进行,但我无法获得正确的代码使其完全按照我的意愿工作。目前这是我的代码:

$type = $_POST['type']; 
$size = $_POST['size']; 
$age = $_POST['age'];
$gender = $_POST['gender']; 
$traits = $_POST['traits']; 
$comments = $_POST['comments']; 
$Name = $_POST['firstn'];
$Email = $_POST['email']; 
// the name of the file you're writing to
$myFile = "info.txt";
// opens the file for appending (file must already exist)
$fh = fopen($myFile, 'a');
// Makes a CSV list of your post data
$colon_delmited_list = implode(",", $_POST) . "'n";
// Write to the file
fwrite($fh, $colon_delmited_list);
// You're done
fclose($fh);

这会写入一个文本文件,内容写为:

Circle,大号,11,男,聪明,非常漂亮,Kyle,Kyle@gmail.com

我从php页面获取所有这些值,但是我希望文件中的值用冒号而不是逗号分隔,并且我还希望实现一个计数,其中每个条目都有编号。

这里有一个例子:

1:圆圈:大:11:男:聪明:非常好:凯尔:Kyle@gmail.com

2:方形:小:14:女性:聪明:非常漂亮:凯莉:Kylie@gmail.com

代码本身非常简单,如果你有一个循环,你会做:

$c = 1; // counter
// inside the loop
$colon_delmited_list = implode(": ", array_merge(array($c++), $_POST)) . "'n";

此行创建一个临时数组,该数组由计数器加上您正在使用的原始数组元素组成,用冒号(和空格)分隔。有很多方法可以做到,这只是我发现最快的一种。

如果计数器是动态的(一直附加到文件中),则应首先计算文件中的行数,然后将其递增一。

显然,您只需要更改内爆()函数使用的粘合参数(有关更多详细信息,请参阅其文档)。

话虽如此,你必须将内爆线更改为:

$colon_delmited_list = implode(":", $_POST) . "'n";