123
-=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- (c) WidthPadding Industries 1987 0|638|0 -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=-
Socoder -> Web Development -> Php and .txt files

Thu, 21 Jun 2007, 12:39
iusinbello
I need to extract some lines from a .txt file via Php.
I am using this code:


<?php
$i=0;
$fd = fopen ("file.txt", "r");
while (!feof ($fd)) {
$buffer = fgets($fd, 409);
$righe[$i] = $buffer;
$i++;
}
fclose ($fd);
?>


But it doesn't always work (Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 4194304 bytes) in /aaa/ggg.php on line 65).
And it is REALLY slow.

So, what code should I use?


-=-=-


Thu, 21 Jun 2007, 15:06
Stealth
In PHP, fgets() is a bad command to scan large files with. It's really slow.

Try this:



I haven't tested that code but I'm pretty sure it will work. I used file() instead of the PHP file functions, it automatically creates an array out of the file without any work. So now $fd is an array with every line of the file. Then the while loop steps threw each line and trims down the length of each line to 409 characters, which it looks like you were doing in your code, if not, you can remove the while loop entirely.

-=-=-
Quit posting and try Google.
Thu, 21 Jun 2007, 15:11
Jayenkai
I can't see anything particularly wrong with that.

Assuming that line 65 is actually to do with this code, and that file.txt isn't ludicrously huge, I see no obvious reasons why it wouldn't work.

Any possibility of you posting a little more code?

|edit| True, Stealth, the ye-olde file commands are slow, but if he really shouldn't be getting "Out of Memory" issues..! |edit|

|edit| 2 : Are you sure the thing's even picking up the file, at all? I've not used file access for a while, so remind me... If the file isn't open, would the loop still be performed? |edit|



-=-=-
''Load, Next List!''
Thu, 21 Jun 2007, 15:13
Stealth
I'm thinking he ran out of RAM on the server or something.. I don't know. But again, fgets() is a REALLY bad function to use when reading large files. It's incredibly slow.

-=-=-
Quit posting and try Google.
Fri, 22 Jun 2007, 13:14
iusinbello
Thank you a lot, stealthspc!
Neat code...
But, for anyone who will use that code, remeber to set "i" to 0 like here:


Or the array will not memorize the first line of your document!



-=-=-