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 ?
file()
function return the data in array - file function
file_get_contents()
return the data in string form Try file_get_contents()
- file_get_contents
$myfile = "data.txt" ;
$getdata = file_get_contents($myfile) ;
$arr = explode('&',$getdata);
print_r($arr); // Will work
file()
returns an array of the lines of the file, so this is the main problem. You will also find that file()
will, by default, include a new line on the end of each line - which you probably don't want.
This code uses array_walk()
to process each line, using explode()
on a line at a time, replacing the original line with the array.
$getdata = file($myfile, FILE_IGNORE_NEW_LINES);
array_walk ( $getdata, function ( &$data ) { $data = explode("&", $data);});
print_r($getdata);
This outputs...
Array
(
[0] => Array
(
[0] => student
[1] => class
[2] => mark
[3] => grade
)
)