I am trying to read every line of a text file into an array and have each line in a new element.
My code so far.
<?php
$file = fopen("members.txt", "r");
$i = 0;
while (!feof($file)) {
$line_of_text = fgets($file);
$members = explode('\n', $line_of_text);
fclose($file);
?>
Obviously, you'll need to create a file handle first and store it in
$file
.It's just easy as that:
file_get_contents()
- gets the whole file as string.explode("\n")
- will split the string with the delimiter"\n"
- what is ASCII-LF escape for a newline.But pay attention - check that the file has UNIX-Line endings.
if
"\n"
will not work properly you have a other coding of2 newline and you can try"\r\n"
,"\r"
or"\025"
You were on the right track, but there were some problems with the code you posted. First of all, there was no closing bracket for the while loop. Secondly, $line_of_text would be overwritten with every loop iteration, which is fixed by changing the = to a .= in the loop. Third, you're exploding the literal characters '\n' and not an actual newline; in PHP, single quotes will denote literal characters, but double quotes will actually interpret escaped characters and variables.
This will be accept the txt file as array. So write anything to the links.txt file (use one line for one element) after, run this page :) your array will be $file
FILE_IGNORE_NEW_LINES
avoid to add newline at the end of each array elementYou can also use
FILE_SKIP_EMPTY_LINES
to Skip empty linesreference here