I want to count number of files in a php file. I am using CodeIgniter framework.
Currently I have tried this below
$file='contractor.php';
$mypath= 'application/controller/'.$file;
$linecount = 0;
$handle = fopen($mypath, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
echo $linecount;
Currently after executing the file in a function it keeps loading. i want to find number of lines in the file.like
output: 202
Try this one hope this will work for you :)
$file = 'getinvoice';
no_of_lines = count(file($file));
echo "number of lines $file";
Your code looks good.
I suppose that the function keeps loading because the file is too big.
Check this answer for an efficient approach to the problem:
Efficiently counting the number of lines of a text file. (200mb+)
$file = basename($_SERVER['PHP_SELF']);
$no_of_lines = count(file($file));
echo "There are $no_of_lines lines in $file"."\n";
If your files are quite small, you could try something like this.
$lines=file($filename);
$count=count($lines);
Related
I have written a php script which parses this text file
http://www.powerball.com/powerball/winnums-text.txt
Everything is good, but I wish to control the amount that is download i.e. I do not need every single result maybe max the first 5. At the moment I am downloading the entire file (which is a waste of memory / bandwidth).
I saw the fopen has a parameter which supposed to limit it but whatever value I placed in has no effect on the amount of text that is downloaded.
Can this be done? Thank you for reading.
Here is a small snippet of the code in question which is downloading the file.
<?php
$file = fopen("http://www.powerball.com/powerball/winnums-text.txt","rb");
$rows = array();
while(!feof($file))
{
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
}
fclose($file);
?>
Thanks everyone this is the code which just downloads the first row of results
while(!feof($file))
{
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
if(count($rows)>1)
{
break;
}
}
fclose($file);
You can break whenever you don't need more data. In this example when count($rows)>100
while(!feof($file)) {
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
if (count($rows)>100)
break;
}
The issue is that your while condition is only met once you've read through to the end of the file. If you only want to get the first N lines you'll need to change that condition. Something like this might help get you started:
$lineCountLimit = 5;
$currentLineCount = 0;
while($currentLineCount < $lineCountLimit)
{
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
$currentLineCount++;
}
Please try the following recipe to download only a part of the file, like 10 KBytes first, then split to lines and analyze them. How to partially download a remote file with cURL?
I have a huge txt file that have 475254 lines and with php I want to read the first line of the my txt file and save it into the Variable and then when I save it the php delete that line.
my txt file is about 2.3 MB is it possible to do this?
yes it is /.................................
OK less trolling..
You want fopen and fgets will grab a line. REF : fgets Manual PHP
$file = "file.txt"
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f); // You close because you only want the first one.
There are so many examples how to do this i feel embarrassed answering. You should show some of what you have tried first!
Now you want to remove it: use file_get_contents REF : PHP file_get_contents
//Get your file contents
$newDoc = file_get_contents($file, true);
$newFileContents = substr( $line, strpos($newDoc, "\n")+1 );
//then you want to save it
file_put_contents($newFileContents, $file);
I might be wrong but you get the idea!~ ;)
Process :
Get Contents of file
Get First Line
Replace content of all file with your First Line as New Line
Save File
Im sure there is a more efficient way to do this, im just winging!
NOTE: You may need to configure your php.ini to work with larger files!
yes, Mark is probably too lazy to even try bulid a code, but i have already a working code so.. copypasta
$file = "mydata.txt";
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
//do smth
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));
//sleep(1);
I have excel(file.xls)/csv(file.csv) file that contains/will contain hundreds of thousands of entry, even millions I guess. Is it possible to split this one to multiple file? Like file.xls to file1.xls, file2.xls, file3.xls and so on.
Are there any libraries to use? Is this possible on PHP? or how about javascript?
On where I can specify how many rows to be included on each file?
Thanks
Quick and dirty way of splitting a CSV file into several CSV files
$inputFile = 'input.csv';
$outputFile = 'output';
$splitSize = 10000;
$in = fopen($inputFile, 'r');
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
}
$data = fgetcsv($in);
if ($data)
fputcsv($out, $data);
$rowCount++;
}
fclose($out);
Yes it is possible to do that in PHP and with CSV files. You basically iterate over the large file and chunk each X rows, forwarding those rows to another file.
You find the information how to open the large CSV file as an iterator in this answer here:
Answer to "how to extract data from csv file in php"
Then you need to chunk the iterator each X rows parts. That can be done as outline here:
Answer to "Need some advice with PHP loop"
Just instead of outputting into multiple <ul>...</ul> HTML lists, you copy over into a new files. That basically works like outlined in:
Answer to "How can I split a CSV file in PHP?"
However this time you want to use the SplFileObject::fputcsv method. Take care you use the latest stable PHP for this, otherwise you need do different, see fputcsv().
If the first line of the original file contains column-headers, you might be as well interested in the following:
Answer to "Process CSV Into Array With Column Headings For Key"
It just shows some ways to extend / process the incomming file. You might not need the full abstraction done there, just keeping the first line around might do it already.
I think You can also use "split by file size":
$part = 1;
$maxSize = 50;//50 Mb
$fopen = fopen('filename.csv','r') or die ('ERROR');
while (($line = fgetcsv($fopen, 10000, ";")) !== FALSE) {
$ftowrite = fopen("Part_$part.csv",'a');
fputcsv($ftowrite,$line);
clearstatcache();
$size = filesize ( "review_p$part.csv" ) / 1000000;
if ($size > $maxSize) {
fclose($ftowrite);
$part++;
}
}
This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
Hi I want to append a row at the beginning of the file using php.
Lets say for example the file is containing the following contnet:
Hello Stack Overflow, you are really helping me a lot.
And now i Want to add a row on top of the repvious one like this:
www.stackoverflow.com
Hello Stack Overflow, you are really helping me a lot.
This is the code that I am having at the moment in a script.
$fp = fopen($file, 'a+') or die("can't open file");
$theOldData = fread($fp, filesize($file));
fclose($fp);
$fp = fopen($file, 'w+') or die("can't open file");
$toBeWriteToFile = $insertNewRow.$theOldData;
fwrite($fp, $toBeWriteToFile);
fclose($fp);
I want some optimal solution for it, as I am using it in a php script. Here are some solutions i found on here:
Need to write at beginning of file with PHP
which says the following to append at the beginning:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
And other one here:
Using php, how to insert text without overwriting to the beginning of a text file
says the following:
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
So my final question is, which is the best method to use (I mean optimal) among all the above methods. Is there any better possibly than above?
Looking for your thoughts on this!!!.
function file_prepend ($string, $filename) {
$fileContent = file_get_contents ($filename);
file_put_contents ($filename, $string . "\n" . $fileContent);
}
usage :
file_prepend("couldn't connect to the database", 'database.logs');
My personal preference when writing to a file is to use file_put_contents
From the manual:
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
Because the function automatically handles those three functions for me I do not have to remember to close the resource after I'm done with it.
There is no really efficient way to write before the first line in a file. Both solutions mentioned in your questions create a new file from copying everything from the old one then write new data (and there is no much difference between the two methods).
If you are really after efficiency, ie avoiding the whole copy of the existing file, and you need to have the last inserted line being the first in the file, it all depends how you plan on using the file after it is created.
three files
Per you comment, you could create three files header, content and footer and output each of them in sequence ; that would avoid the copy even if header is created after content.
work reverse in one file
This method puts the file in memory (array).
Since you know you create the content before the header, always write lines in reverse order, footer, content, then header:
function write_reverse($lines, $file) { // $lines is an array
for($i=count($lines)-1 ; $i>=0 ; $i--) fwrite($file, $lines[$i]);
}
then you call write_reverse() first with footer, then content and finally header. Each time you want to add something at the beginning of the file, just write at the end...
Then to read the file for output
$lines = array();
while (($line = fgets($file)) !== false) $lines[] = $line;
// then print from last one
for ($i=count($lines)-1 ; $i>=0 ; $i--) echo $lines[$i];
Then there is another consideration: could you avoid using files at all - eg via PHP APC
You mean prepending. I suggest you read the line and replace it with next line without losing data.
<?php
$dataToBeAdded = "www.stackoverflow.com";
$file = "database.txt";
$handle = fopen($file, "r+");
$final_length = filesize($file) + strlen($dataToBeAdded );
$existingData = fread($handle, strlen($dataToBeAdded ));
rewind($handle);
$i = 1;
while (ftell($handle) < $final_length)
{
fwrite($handle, $dataToBeAdded );
$dataToBeAdded = $existingData ;
$existingData = fread($handle, strlen($dataToBeAdded ));
fseek($handle, $i * strlen($dataToBeAdded ));
$i++;
}
?>
I am trying to read a bin file that contains a lots of two 4-byte numbers in it, which I want to read and convert to hex numbers that is then going to be printed to the screen.... hopefully however I am having a little trouble getting my head around this one. this is what I have so far from reading examples and documentation..
<?php
$handle = #fopen("files/bigbin1.bin", "r");
if ($handle) {
while (!feof($handle)) {
$hex = bin2hex($handle);
}
fclose($handle);
}
print_r($hex);
?>
I am 95% sure the error is in passing $handle over to tbin2hex.. but this being my first ever reading of a bin file I am slightly lost. the overall goal at some point will be to read the bin file into the database however I am just trying to figure out what this file looks like on screen.
<?php
$handle = #fopen("files/bigbin1.bin", "r");
if ($handle) {
while (!feof($handle)) {
$hex = bin2hex(fread ($handle , 4 ));
print $hex."\n";
}
fclose($handle);
}
?>
EDIT: Also you should avoid using # it can make debugging extremely frustrating.