read textfile with delimiter in php
I have three eintries in a textfile.txt:
20100220
Hello
Here is Text \n blah \t even | and & and so on...
I want to read each entrie (line) as a new string in php. I thought of using fopen and fgets. But: Since I'm using special characters like \n in the last line, fgets() would not work because it will terminate the string at \n, right? In a result the last line would be just 'Here is 开发者_JAVA技巧Text '.
How can I read/explode the three lines the right way, so the \n in the last line would be interpreted as a normal string? Thanks!
p.s. By having three lines in my textfile.txt I indirect chose \n as a delimiter, but I could also use another delimiter. what is just the best way to read the content?
You have two options:
1.- Use file() to get an array with an element for each line (separated by '\n')
$lines_of_file = file("myfile.txt");
//Now $lines_of_file have an array item per each line
2.- Use file_get_contents() to get a single string you can then split by any separator you want
$file_content = file_get_contents("myfile.txt");
$file_content_separated_by_spaces = explode(" ", $file_content);
Use file()
, that will automatically give you an line-by-line array:
$rows = file('textfile.txt');
And even if you use fgets and such, you should be able to explode properly with "\n"
as it is treated differently than literal '\n'
.
精彩评论