I´m having trouble exploding contents of a .txt file (structure below):
01Name 1
02whatever contents
03whatever contents
-------------------
01Name 2
02whatever contents
03whatever contents
As you can see, the "delimiter" is "-------------------". Now, the question is: how to explode this file into an array, so I can search for a specific name and display that block´s contents? I´ve tried to explode like this:
header("Content-type:text/plain");
$file = fopen("cc/cc.txt", "r");
while (!feof($file)) {
$lot = fgets($file);
$chunk = explode("-------------------",$lot);
print_r($chunk);
}
fclose($file);
And got this as a result:
Array
(
[0] => 01Name 1
)
Array
(
[0] => 02whatever contents
)
Array
(
[0] => 03whatever contents
)
Array
(
[0] => -------------------
)
Array
(
[0] => 01Name 2
)
Array
(
[0] => 02whatever contents
)
Array
(
[0] => 03whatever contents
)
when i wanted to get this as a result:
Array
(
[0] => 01Name 1
[1] => 02whatever contents
[2] => 03whatever contents
)
Array
(
[0] => 01Name 2
[1] => 02whatever contents
[2] => 03whatever contents
)
I´ve searched PHP; assigning fgets() output to an array and Read each line of txt file to new array element , with no luck.
Any thoughts?
If your file is consistently formatted, having three lines per block of data, you could simply parse it that way. Here I am creating a 2-dimensional array of the whole file:
This outputs:
You can use the following
Output
You can take it further
Output
Firstly you should use
file()
to read and split up a file line-wise. That's a built-in specifically for that purpose.Your check for
"-------------------"
fails because you didn't take the trailing linebreaks (\r\n
etc.) into account. (UseFILE_IGNORE_NEW_LINES
for thefile()
function as one solution). Though it might be better to use a regex here:A bit redundant this way, but more resilient.
You might as well read the whole file with
file_get_contents
and split out text blocks withpreg_split
instead.