Get Text File data using in php

时间:2018-06-20 05:03:49

标签: php explode

I have one text file in directory. I want to get contents of that text file.

in my text file

student&class&mark&grade 

I am trying to my code here.

$myfile = "data.txt" ;
$getdata = file($myfile) ;

print_r($getdata) ; // student&class&mark&grade  // working fine.

I'm trying to explode function

$arr = explode('&',$getdata);
print_r($arr); // not working

how to solve this problem ?

2 个答案:

答案 0 :(得分:1)

file()函数返回数组中的数据-file function

file_get_contents()以字符串形式返回数据 尝试file_get_contents()-file_get_contents

$myfile = "data.txt" ;
$getdata = file_get_contents($myfile) ;

$arr = explode('&',$getdata);
print_r($arr); // Will work

答案 1 :(得分:1)

file()返回文件行的数组,因此这是主要问题。您还会发现,file()默认情况下会在每行的末尾添加新行-您可能不希望这样做。

此代码使用array_walk()处理每一行,一次在一行上使用explode(),将原始行替换为数组。

$getdata = file($myfile, FILE_IGNORE_NEW_LINES);
array_walk ( $getdata, function ( &$data ) { $data = explode("&", $data);});
print_r($getdata);

这将输出...

Array
(
    [0] => Array
        (
            [0] => student
            [1] => class
            [2] => mark
            [3] => grade 
        )

)