a1amattyj Posted September 16, 2010 Share Posted September 16, 2010 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!! Quote Link to comment https://forums.phpfreaks.com/topic/213584-read-first-line-of-file/ Share on other sites More sharing options...
wildteen88 Posted September 16, 2010 Share Posted September 16, 2010 You may want to use fopen/fget instead? Quote Link to comment https://forums.phpfreaks.com/topic/213584-read-first-line-of-file/#findComment-1111717 Share on other sites More sharing options...
meltingpoint Posted September 16, 2010 Share Posted September 16, 2010 $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. Quote Link to comment https://forums.phpfreaks.com/topic/213584-read-first-line-of-file/#findComment-1111858 Share on other sites More sharing options...
Andy-H Posted September 16, 2010 Share Posted September 16, 2010 if ( ($fh = fopen('file.txt', 'r')) !== false) { $firstLine = implode(" ", (fgetcsv($fh, 1000, " ")) ); } fclose($fh); Quote Link to comment https://forums.phpfreaks.com/topic/213584-read-first-line-of-file/#findComment-1111860 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.