Reputation:
In php how to get a file by his path and return his content in an array? lets say that I have file: file.txt that have the path:path_file, and the file is TSV like this:
a0 b0
a1 b1
a2 b2
...
how can I access the file and put his content in an array like this:
array(
array(a0,b0),
array(a1,b1),
array(a2,b2),
)
How can I get the file content by the use of the path?
function get_content_file($path_file)
{
$data[];
//open file by path
//read file content
//push the content in an array
return $data;
}
Upvotes: 0
Views: 207
Reputation: 437336
You can already get a file into an array line-by-line with file
. If you want each item in the array to be an array itself then use array_map
to process the lines:
$data = file($path_file);
$data = array_map(function($l) { return explode(" ", $l); }, $data);
If the file's format is not "values separated by a single space" then this code won't work correctly; in that case use an appropriate split function (perhaps preg_split
) to break up each line into tokens.
Upvotes: 1