0

So i want to write to a txt file using php. This txt file containts values for a array. The problem is that when i write in my textfield array[0] gets longer in stead of adding a new line in the array(array[1]). i tried and searched for 3 hours but cant find anything!

<html>
<body>
<form action="arraytest2.php">
  nieuwe regel <input type="text" method = "GET" name="nregel"><br>
  <input type="submit" value="Submit">
</form>


<?php


$file = "./members.txt";
$members = array();

if(isset($_GET['nregel']))
{
    $nregel = $_GET['nregel'];
    file_put_contents($file,$nregel,FILE_APPEND);


}

$members[] = file_get_contents($file);
var_dump($members);

?>
</body>
</html>
4
  • Try with $members = explode("\n",file_get_contents($file)); Commented Mar 26, 2014 at 13:29
  • 4
    @D.Kasipovic: Or just $members = file($file);. Commented Mar 26, 2014 at 13:31
  • True that, well said. Commented Mar 26, 2014 at 13:32
  • ^its not working the string keeps getting longer but dont add a array[1] just making the string longer Commented Mar 26, 2014 at 13:40

3 Answers 3

1

Try add '\n' before the string that you should save...

Something like:

file_put_contents($file, "\n{$nregel}", FILE_APPEND);

And to read like array you'll need to split all file into array... Try something like:

preg_split('/\n/', file_get_contents(...));

Remember... you have more then half path here...

Sign up to request clarification or add additional context in comments.

Comments

0

edit the following line

file_put_contents($file,$nregel,FILE_APPEND);

to read

file_put_contents($file,$nregel."\n",FILE_APPEND);

Comments

0

Write your value every time by appending any delimiter. Delimiter must not be the part of data.

Here I am taking '|' as delimiter

so code to write the file would be

file_put_contents($file, '|'.$nregel, FILE_APPEND);

and to retrieve

$members[] = explode('|', file_get_contents($file));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.