在php中读取带有分隔符的文本文件
我在 textfile.txt 中有三个条目:
20100220
Hello
Here is Text \n blah \t even | and & and so on...
我想将每个条目(行)作为 php 中的新字符串读取。我想到使用 fopen 和 fgets。但是:由于我在最后一行使用了 \n 等特殊字符,因此 fgets() 将不起作用,因为它会在 \n 处终止字符串,对吧?结果最后一行只是“Here is Text”。
如何以正确的方式读取/分解这三行,以便最后一行中的 \n 将被解释为普通字符串? 谢谢!
附注 通过在我的 textfile.txt 中包含三行,我间接选择 \n 作为分隔符,但我也可以使用另一个分隔符。阅读内容的最佳方式是什么?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有两个选择:
1.- 使用 file() 获取数组每行一个元素(用 '\n' 分隔)
2.- 使用 file_get_contents() 获取单个字符串,然后可以按所需的任何分隔符分割
You have two options:
1.- Use file() to get an array with an element for each line (separated by '\n')
2.- Use file_get_contents() to get a single string you can then split by any separator you want
使用
file()
,这将自动为您提供逐行数组:即使您使用 fgets 等,您也应该能够使用
"\n"
正确爆炸,因为它的处理方式与文字' 不同\n'
。Use
file()
, that will automatically give you an line-by-line array: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'
.