php逐行读取文本文件,然后处理空格分隔文本,输出为数组的方法。
文本文档text.txt内容:
<span style="color: #000000;">1 字段1 字段2 2 字段1 字段2 3 字段1 字段2 4 字段1 字段2 </span>
登入後複製
文本和文本之间用空格隔开,用php经过处理,输出为数组,一下是代码
<span style="color: #000000;">php </span><span style="color: #800080;">$file</span> = <span style="color: #008080;">fopen</span>("text.txt", "r") or <span style="color: #0000ff;">exit</span>("Unable to open file!"<span style="color: #000000;">); </span><span style="color: #0000ff;">while</span>(!<span style="color: #008080;">feof</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">)) { </span><span style="color: #800080;">$arr</span> = <span style="color: #008080;">split</span>(' ' , <span style="color: #008080;">fgets</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">)); </span><span style="color: #008080;">print_r</span>(<span style="color: #800080;">$arr</span><span style="color: #000000;">); } </span><span style="color: #008080;">fclose</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">); </span>?>
登入後複製
?输出结果:
<span style="color: #0000ff;">Array</span><span style="color: #000000;"> ( [</span>0] => 1<span style="color: #000000;"> [</span>1] =><span style="color: #000000;"> 字段1 [</span>2] =><span style="color: #000000;"> 字段2 ) </span><span style="color: #0000ff;">Array</span><span style="color: #000000;"> ( [</span>0] => 2<span style="color: #000000;"> [</span>1] =><span style="color: #000000;"> 字段1 [</span>2] =><span style="color: #000000;"> 字段2 ) </span><span style="color: #0000ff;">Array</span><span style="color: #000000;"> ( [</span>0] => 3<span style="color: #000000;"> [</span>1] =><span style="color: #000000;"> 字段1 [</span>2] =><span style="color: #000000;"> 字段2 ) </span><span style="color: #0000ff;">Array</span><span style="color: #000000;"> ( [</span>0] => 4<span style="color: #000000;"> [</span>1] =><span style="color: #000000;"> 字段1 [</span>2] =><span style="color: #000000;"> 字段2 ) </span>
登入後複製
这样就实现了PHP用空格分割文本为数组的方法
本php教程由JS代码站出品