How to skip fwrite() for x lines - php

I'm creating PHP program which should find in *.txt file line that starts with word "tak" and skip that program from rewriting it to the next *.txt file. So what I want to achieve now is prevent it from writing, for example, 2 more lines after line that started with "tak" word. Here is my CODE:
<?php
$file2 = fopen("out.txt", "w") or die("Unable to open file!");
$handle = fopen("plik.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (strpos($line, 'tak') === 0) {
echo 'found<br/>';
}
else {
fwrite($file2, $line);
}
}
fclose($handle);
echo 'OK';
}
else {
echo "can't read the file";
}
?>

I think using file, a for loop, and file_put_contents would work and be simpler.
$file2 = "out.txt";
//$file = file($file2) or die("Unable to open file!");
$file = array('asdf',
'asdf',
'asdf',
'tak',
'1',
'2',
'3',
'4');
file_put_contents($file2, ''); // truncate file;
for($i = 0; $i < count($file); $i++) {
$line = $file[$i];
if (strpos($line, 'tak') === 0) {
echo 'found<br/>';
$i = $i + 2;
} else {
// file_put_contents($file2, $line, FILE_APPEND | LOCK_EX);
echo $line;
}
echo 'ok';
}
Demo: https://eval.in/597694
Output (kinda messy but gets the point tak, 1, and 2 skipped):
asdfokasdfokasdfokfound<br/>ok3ok4ok

You can do it by keeping boolean and integer variable to count the number of occurrence. Like this,
<?php
$file2 = fopen("out.txt", "w") or die("Unable to open file!");
$handle = fopen("plik.txt", "r");
if ($handle) {
$stopWriteLines=false;
$max_line_skip=2;
// Taking above two variables for our logic.
while (($line = fgets($handle)) !== false) {
if($stopWriteLines) {
$max_line_skip--;
}
// Above condition check if we found tak in line then decrements the skip lines count.
if (strpos($line, 'tak') === 0) {
echo 'found<br/>';
$stopWriteLines=true; // Setting Boolean variable to skip writing lines.
}
else {
if(!$stopWriteLines) { // will write only if Boolean variable is set to true.
fwrite($file2, $line);
}
}
if($max_line_skip==0) {
$stopWriteLines=false;
}
// Above condition will make Boolean variable false after skipping 'n' lines.
}
fclose($handle);
echo 'OK';
}
else {
echo "can't read the file";
}
?>
Please check the explanations in code for better understanding of respected code sections.

Related

Grab particular data from row

I have the following peoplelist.txt text file with 2 rows:
1,Hello,hello#me.com,Boss
2,Hello Again,hello2#me.com,Boss
My code to output this is:
$handle = fopen("peoplelist.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
Is it possibly instead of outputting the entire line, I just output the data in the 2nd column (aka Hello & Hello Again)?
Since that's CSV data:
while (($line = fgetcsv($handle)) !== false) {
echo $line[1];
}
$handle = fopen("/temp/peoplelist.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$parts = explode(',',$line);
echo $parts[1] . PHP_EOL;
}
fclose($handle);
}

Php fopen delete each readed line while reading

I have a code
$handle = fopen(getcwd() . "/emails.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
SendEmails($line,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
$line.delete; // here i need to delete each readed line
}
fclose($handle);
} else {
echo "error opening the file.";
}
How to delete each readed line while reading?
Try This
$handle = fopen(getcwd() . "/emails.txt", "r");
$readedlines="";
if ($handle) {
while (($line = fgets($handle)) !== false) {
SendEmails($line,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
$readedlines=$readedlines.$line;
fclose($handle);
$newFileContent=str_replace($readedlines,"",file_get_contents($filename));
$handle=fopen($filename, "w");
fwrite($handle,$newFileContent);
fclose($handle);
} else {
echo "error opening the file.";
}
I mean just concate all readed line into one string and replace through the whole string of file content.
Hope that helps
// Get file contents
$contents = file_get_contents('/emails.txt');
// Explode to get contents in an array
$rows = explode("\n", $contents);
file_put_contents('/emails.txt', "");
// Loop through all rows in emails.txt
foreach ($rows as $row) {
// If sending the email fails, add row to $notSent
if (false === SendEmails($row, $strSubject, $strMessage, $txtFormName, $txtFormEmail, $fname, $ftype,$tmp_path)) {
$contents = file_get_contents('/emails.txt');
$contents .= $row."\n";
file_put_contents('/emails.txt', $contents);
}
}

PHP function to download and overwrite the previews downloaded file

I am using the following code to download an archived csv file and uncompress it:
$url="http://www.some.zip";
$target = 'data-' . md5(microtime()) . '.zip';
function download($src, $dst) {
$f = fopen($src, 'rb');
$o = fopen($dst, 'wb');
while (!feof($f)) {
if (fwrite($o, fread($f, 2048)) === FALSE) {
return 1;
}
}
fclose($f);
fclose($o);
return 0;
}
download($url,$target);
if ( file_exists($target) ){
echo "Download Successuful <br />";
$arc = new ZipArchive;
if (true !== $arc->open($target)) {
echo "Unzipping Failed <br />";
}else {
file_put_contents($out, $arc->getFromIndex(0));
echo "Unzipping Successuful <br />";
fclose($handle);
}
}else {
echo "Download Failed <br />";
}
However, on a second run, it does't do anything and I would like to overwrite the initial file with the newer file. (the CSV File)
How should I do that? The solution should take about the same time as the first download!
The easiest solution would be to first check if the file exists, then remove it.
function download($src, $dst) {
if(file_exists($dst)) unlink($dst);
$f = fopen($src, 'rb');
$o = fopen($dst, 'wb');
while (!feof($f)) {
if (fwrite($o, fread($f, 2048)) === FALSE) {
return 1;
}
}
fclose($f);
fclose($o);
return 0;
}

How to skip the first line of CSV in PHP

I have a CSV upload that I am struggling to get to skip the first line of the CSV document. I am uploading a single CSV document and the first line contains a cell that contains one bit of text which is throwing out the array. I am not sure which count to edit?
$fields_firstrow = true;
$i = 0;
$a = 0;
$fields = array();
$content = array();
$allowedExts = array("csv");
$extension = end(explode(".", $_FILES["file"]["name"]));
if (($_FILES["file"]["size"] < 2000000)&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists($_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
$file = $_FILES["file"]["name"];
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if($fields_firstrow == true && $i<1) {
foreach($data as $d) {
$fields[] = strtolower(str_replace(" ", "_", $d));
}
$i++;
continue;
}
$c = 0;
foreach($data as $d) {
if($fields_firstrow == true) {
$content[$a][$fields[$c]] = $d;
} else {
$content[$a][$c] = $d;
}
$c++;
}
$a++;
}
} else {
echo "Could not open file";
die();
}
Any help would be greatly appreciated.
Just add an extra line of code before the line from where the while loop starts as shown below :
....
.....
fgetcsv($handle);//Adding this line will skip the reading of th first line from the csv file and the reading process will begin from the second line onwards
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
.......
.......
It is just as simple........ !!!
$i=0;
if($fields_firstrow == true) {
foreach($data as $d) {
if ($i == 0){continue;}
$i++;
$fields[] = strtolower(str_replace(" ", "_", $d));
}
}
You are not changing the value for variable $fields_firstrow. For all loop iteration it will still be true.
In my opinion and per my understand of your code, you should change it to false before the first continue.
...
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if($fields_firstrow == true && $i<1) {
foreach($data as $d) {
$fields[] = strtolower(str_replace(" ", "_", $d));
}
$i++;
$fields_firstrow = false;
continue;
}
$c = 0;
foreach($data as $d) {
if($fields_firstrow == true) {
$content[$a][$fields[$c]] = $d;
} else {
...
Maybe you do not need the $i variable after that.
Here is an example from http://php.net/fgets modified a bit:
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
$firstLine = true;
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if(firstLine) {
$firstLine = false;
continue;
}
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
I assume you see the point, and can modify your script accordingly.

Remove Line From CSV File

I have .csv file with 4 columns. What's the easiest way to remove a line identical with the id of the first column? Here's where I got stuck:
if($_GET['id']) {
$id = $_GET['id'];
$file_handle = fopen("testimonials.csv", "rw");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($id == $line_of_text[0]) {
// remove row
}
}
fclose($file_handle);
}
Unfortunately, databases were not a choice.
$table = fopen('table.csv','r');
$temp_table = fopen('table_temp.csv','w');
$id = 'something' // the name of the column you're looking for
while (($data = fgetcsv($table, 1000)) !== FALSE){
if(reset($data) == $id){ // this is if you need the first column in a row
continue;
}
fputcsv($temp_table,$data);
}
fclose($table);
fclose($temp_table);
rename('table_temp.csv','table.csv');
I recently did a similar thing in for a newsletter unsubscription, heres my code:
$signupsFile = 'newsletters/signups.csv';
$signupsTempFile = 'newsletters/signups_temp.csv';
$GLOBALS["signupsFile"] = $signupsFile;
$GLOBALS["signupsTempFile"] = $signupsTempFile;
function removeEmail($email){
$removed = false;
$fptemp = fopen($GLOBALS["signupsTempFile"], "a+");
if (($handle = fopen($GLOBALS["signupsFile"], "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
if ($email != $data[0] ){
$list = array($data);
fputcsv($fptemp, $list);
$removed = true;
}
}
fclose($handle);
fclose($fptemp);
unlink($GLOBALS["signupsFile"]);
rename($GLOBALS["signupsTempFile"], $GLOBALS["signupsFile"]);
return $removed;
}
this uses the temp file method of writing out the csv line by line to avoid memory errors. Then once the new file has been created, it deletes the original and renames the temp file.
You can modify this code so that it looks for an ID instead of an email address eg:
$id = $_GET['id'];
$fptemp = fopen('testimonials-temp.csv', "a+");
if (($handle = fopen('testimonials.csv', "r")) !== FALSE) {
while (($id= fgetcsv($handle)) !== FALSE) {
if ($id != $data[0] ){
$list = array($data);
fputcsv($fptemp, $list);
}
}
fclose($handle);
fclose($fptemp);
unlink('testimonials.csv');
rename('testimonials-temp.csv','testimonials.csv');
$id = $_GET['id'];
if($id) {
$file_handle = fopen("testimonials.csv", "w+");
$myCsv = array();
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0]) {
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
You can do:
$new = '';
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
$new .= implode(',',$line_of_text) . PHP_EOL;
}
}
basically you running threw each line and check if the id does NOT match the id sent in the get parameter, if it does not then it writes the line to the new container / variable.
And then rewrite the $new value to the file, this should work ok:
How big is the file
Do you have a CSV Header on line 0?
I have found a solution, that does not need to copy the file.
$file = 'testimonials.csv'
// open two handles on the same file
$input = fopen($file ,'r'); // read mode
$output = fopen($file, 'c'); // write mode
if($input !== FALSE && $output !== FALSE) { // check for error
while (($data = fgetcsv($input, $CSVLIMIT, $sep)) !== FALSE) {
if(reset(data) == $id) {
continue;
}
fputcsv($output, $data, $sep);
}
// close read handle
fclose($input);
// shorten file to remove overhead created by this procedure
ftruncate($output, ftell($output));
fclose($output);
}
Note: only one of those fopen commands could fail, leaking the handle for the second one. It would be good, to check both handles independetly and close them on a error.

Categories