Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.