-1

So What I have currently is working, however I just cant get the right code to make it work exactly as I would like. Currently this is my code:

$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);

This writes to a text file and the contents are written as:

Circle, Large, 11, Male, Smart, very nice, Kyle, Kyle@gmail.com

I get all these values from a php page, however I want the values in the file to be separated by colons rather than commas, and I also want to implement a count where each entry is numbered.

Here is an example:

1:Circle: Large: 11: Male: Smart: very nice: Kyle: Kyle@gmail.com

2:Square: Small: 14: Female: Smart: very nice: Kylie: Kylie@gmail.com

Community
  • 1
  • 1
joe dirt
  • 75
  • 8
  • 2
    change the comma with a colon in implode – Ibu Apr 12 '16 at 22:31
  • oh wow for some reason I swear I tried that and it didn't work, however now it does I must have messed something up when I first tried it! – joe dirt Apr 12 '16 at 22:34
  • Thank you :) now I'm just stuck on implementing a counter – joe dirt Apr 12 '16 at 22:35
  • And for adding a count, first read the file and get the most recent counter. Then increment by 1 and output it before the rest of the data. (Although be aware there will be concurrency issues surrounding this so you may also have to implement exclusive file locking.) – Chris Apr 12 '16 at 22:36

2 Answers2

2

The code itself is very simple, if you have a loop, you'd do:

$c = 1; // counter

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

This line creates a temporary array that consists of the counter plus the original array elements you were using, separated by a colon (and a space). There are tons of ways to do it, this is just the one I found to be the quickest.

If your counter is dynamic (appending to the file all the time), you should first count the number of lines in the file and then just increment it by one.

Community
  • 1
  • 1
Shomz
  • 37,421
  • 4
  • 57
  • 85
1

Obviously, you only need to change the glue parameter used by implode() function (see its doc for more details).

That being said, you must change the implode line to :

$colon_delmited_list = implode(":", $_POST) . "\n";
Matt
  • 256
  • 1
  • 9