To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.
If you don't need any special processing, this should do what you're looking for
$lines = file($filename, FILE_IGNORE_NEW_LINES);
The fastest way that I've found is:
// Open the file
$fp = @fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
where $filename is going to be the path & name of your file, eg. ../filename.txt.
Depending how you've set up your text file, you'll have might have to play around with the \n bit.
Just use this:
$array = explode("\n", file_get_contents('file.txt'));
$yourArray = file("pathToFile.txt", FILE_IGNORE_NEW_LINES);
FILE_IGNORE_NEW_LINES
avoid to add newline at the end of each array element
You can also use FILE_SKIP_EMPTY_LINES
to Skip empty lines
reference here
<?php
$file = fopen("members.txt", "r");
$members = array();
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
var_dump($members);
?>
It's just easy as that:
$lines = explode("\n", file_get_contents('foo.txt'));
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 another coding of newline and you can try "\r\n"
, "\r"
or "\025"
$lines = array();
while (($line = fgets($file)) !== false)
array_push($lines, $line);
Obviously, you'll need to create a file handle first and store it in $file
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With