Reputation: 13
first, i have a text file
Samsung|us|new
iPhone|china|new
i want to convert the text file, and the result must be like this
[
[
'Samsung', 'us', 'new'
],
[
'iPhone', 'china', 'new'
]
]
i have already try this, but the code only return one array
code:
<?php
$a = file_get_contents("text.txt");
$b = explode('|', $a);
result:
[
'Samsung','us','new','iPhone','china','new'
];
Upvotes: 1
Views: 154
Reputation: 2589
This is because file_get_contents()
reads the whole file including the line breaks.
You have to first explode()
on \n
. After that explode()
on |
.
Or with array_map()
in one line:
$a = file_get_contents("text.txt");
$b = array_map(fn($line) => explode('|', $line), explode("\n", $a));
// $a with \n
// this explode splits the lines
// this explodes at the | character
Example: https://3v4l.org/24qla
If you want to read some big files you can use something like this:
function getCsvData($file, $delimiter = '|') {
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
yield $data;
}
fclose($handle);
}
}
foreach(getCsvData('test.txt') as $row) {
print_r($row);
}
Upvotes: 0
Reputation: 889
According to the hint from Jeto I would do the following:
at first read the file with function file() with the flag FILE_IGNORE_NEW_LINES
. This reads the file line by line and creates an array.
next step would be to iterate over each element and split by |
character with explode().
This could be the resulting code:
$file = file('test.txt', FILE_IGNORE_NEW_LINES);
for($i = 0; $i < count($file); $i++)
{
$file[$i] = explode('|', $file[$i]);
}
Upvotes: 1
Reputation: 27295
Don't use file_get_contents
open the file and read the file line by line. Then split the line.
https://www.php.net/manual/en/function.fgets.php
Here are some example to do this. You can use fgets
for this. With file_get_contents
you get the whole file.
Another solution is to explode by \r\n
or \n
the characters for new line. Then you have the single lines and you can split them by your delimiter. But in this case you write the whole content in an array what can cause some memory problem.
explode("\n",$homepage)
Upvotes: 0