Jump to content

Read first line of file


a1amattyj

Recommended Posts

Hello,

 

I'm trying to read the first line of some large files by PHP, which means, the ideal solution does not work:

 

$content = file($file_import);

 

$fields = explode(",", $content[0]);

 

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 110 bytes) in C:\wamp\www\exchange\admin\import.php on line 55

 

Is there any other way to read only the first line without opening the whole file?

 

Thanks!!

Link to comment
https://forums.phpfreaks.com/topic/213584-read-first-line-of-file/
Share on other sites

$record_count =1;
$openedfile	=fopen("yourfile.txt", "r");
if(!$openedfile)
{
echo "<center>Error!  Could not open file</center>";
exit;
}
if(flock($openedfile, LOCK_EX))
{
//
$hold[$record_count] = explode(",", trim(fgets($openedfile)));// the "," is what your flat file is delimited by
while(!feof($openedfile))
{
$record_count++;
$hold[$record_count] = explode("|", trim(fgets($openedfile)));
}
flock($openedfile, LOCK_UN);
fclose($openedfile);
}
else
{
echo "<center>File could not be locked - please try again.</center>";
}
print_r( $hold[1]); // is an array containing the contents of the first line of your file.

 

So now you could simply reference the first line of you file as $hold[1].  It is just another way of doing what you had done earlier.  However- that file is 128mb in size.  Most systems limit to 64 mb.  Might want to check and see of it is limited in php.ini file.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.