Delete current iterating row from CSV file in PHP - php

I want to delete current iterating row from CSV file,
Suppose I have 5 rows (1,2,3,4,5) into my CSV file, I opened my file while iterating the rows one by one using foreach, when it comes to 3rd row then 3rd row should be deleted from CSV file and other 1,2,4,5 rows will be same while same iterration. I don't want to use like Skip the 3rd iterration and save it into another file, not like rename file name. So, Please anyone can help me how to do this in PHP?
Suppose, like SQL command to delete current row, is there anything in PHP?
Thanks.

You will need to have permissions to write the file. If you remove a row, you will have to save the file. As you do not want to have any empty rows as well, you need to read the whole file.
I suggest to get the file content, and split it into a array by lines. With the explode function you can split the content by the line break, most likely "\n". So an array wich will contain each line of the csv file will be existing. Now you can simply remove the line from the array and create a string out of it, before saveing the changed content back to the csv file.
// get csv content into string variable
$csvContent = file_get_contents(__DIR__ . "/yourfile.csv");
// create array out of csv, limited by PHP_EOL wich determines the systems line break
// this means, every line in the csv file will be represended by an array key and its value
$csvArray = explode(PHP_EOL, $csvContent);
// unset the 3th csv line.
unset($csvArray[2]); // keep in mind array starts at 0, so third line is array key 2
// from here on you can manipulate the array $csvArray as you like.
// add lines, remove lines or just use the given content for future operations.
// you can also iterate over the array with: foreach ($csvArray as $line => $value) {}
// create string out of modified csv array
$csvContent = implode(PHP_EOL, $csvArray);
// save result back into the csv file
file_put_contents( __DIR__ . "/yourfile.csv", $csvContent);
Check implode/explode php function docs:
http://php.net/manual/en/function.implode.php
http://php.net/manual/en/function.explode.php

Related

Delete CSV Rows

How would I go about deleting a specific number of rows from a large csv file? ie, I am looking to delete the first 100 rows from a file containing over 200,000 rows. Just curious to see if there is another way to handle things other than completely re-writing the file to a temp file and back to overwrite the original file.
Thanks in advance for any help/suggestions.
Does it need to be in php?
You can use the unix command tail to print every line in a file starting from the nth line:
tail -n +101 file.csv > trimmed.csv
Or using PHP:
$lines = file('file.csv'); // read file as array of lines
$trimmed = array_slice($lines, 100); // slice array at index
file_put_contents('trimmed.csv', implode($trimmed)); // implode and write to file

comma separated in text file in php

if(isset($_POST['submit']))
{
$file = $_FILES['file']['name'];
$fh = fopen($file,'r+');
// string to put username and passwords
$users = '';
while(!feof($fh)) {
$user = explode(' ',fgets($fh));
foreach ($user as $value)
{
$number= rand(1000,10000);
$final_number[] = $value .','. $number;
}
}
//print_r($final_number);
file_put_contents($_FILES['file']['name'], $final_number);
}
this is my code for appending a random text to a string with comma and save it in text file but when i am saving it it is not saving properly after comma it is going to next line which should not happen plzz.. help me
Your code starts with a very big issue: you try to open and read from a file that, most probably, doesn't exist.
$file = $_FILES['file']['name'];
$fh = fopen($file,'r+');
As you can read in the documentation, assuming that your form contains an input element of type file having the name file, $_FILES['file']['name'] is the original name of the uploaded file, on the user's computer. It is only the name and it is not the name of the file on the server. It is provided just as a hint for the file's content (check the filename extension) but you cannot rely on it.
The content of the file is temporarily stored on the webserver in a file whose path can be found in $_FILES['file']['tmp_name']. You should pass it to the PHP function is_uploaded_file() to be sure the file was uploaded and your script is not the victim of an injection attempt then, if you need to keep it, use move_uploaded_file() to move it where you need. If you don't move it, when your script ends the temporary file is deleted.
Another problem of your code is on the lines:
$user = explode(' ',fgets($fh));
foreach ($user as $value)
As explained in the documentation, the function fgets() called without a second argument reads a line from the input file, including the newline character that ends it. Since you split the line into words I think you don't need the newline character. You can remove it by using trim() with the string returned by fgets() before passing it to explode().
The last issue of the code is:
file_put_contents($_FILES['file']['name'], $final_number);
Because $final_number is an array1, file_put_contents() joins its elements to get a string and writes the string into file. This operation concatenates the random value generated for a $value with the next $value and there is no way to tell which is which after the data is stored in the file. You probably need to keep them on separate lines. Use function implode() on $final_number, with "\n" as its first argument and write the generated string into the file instead.
The last one: don't write the generated content to $_FILES['file']['name']. It is not safe! It contains a string received from the browser; a malicious user can put whatever path they want there and your script will overwrite a file that it shouldn't change.
Create a directory dedicated to store files generated by your code and generate filenames based on an always incremented counter (the current time() or microtime() f.e.) for the files you store there. Never trust the data you receive from the browser.
1 $final_number is used as $final_number[] = ... and, because it is not defined when this line of code is executed for the first time, PHP creates an empty array for you and stores it in $final_number. Don't rely on this feature. Always initialize your variables before their first use. Put $final_number = array(); before the while().
I am going to use a different approach than you, let's say that the data you want to save to the file is stored in the variable $data.
So to append this data to the file with a comma at first, we can use just two lines of code:
$previousFileContent = file_get_contents("filename.txt");
file_put_contents("filename.txt", trim($previousFileContent . "," . $data));

How to delete array in text file PHP

I have a text file. I want to delete some lines with a query of search.
The array is line by line. I want to made it like http://keywordshitter.com/
The logic is,
SEARCH --> IN ARRAY --> OUTPUT IS ARRAY WITHOUT "QUERY OF SEARCH"
Code I have tried:
$fileset = file_get_contents("file.txt");
$line = explode("\n", $fileset);
$content = array_search("query",$line);
print_r($content);
MY file.txt
one
two
three
apple
map
I have used array_search but not working.
you can do search like
$fileset=file("file.txt"); // file function reads entire file into an array
$len=count($fileset);
for($i=0;$i<$len;$i++)
{
if($fileset[$i]=="query")
{
$fileset[$i]="";
break; //then we will stop searching
}
}
$fileset_improve=implode($fileset); //this will again implode your file
$handle=fopen("file.txt","w"); //opening your file in write mode
fwrite($handle,$fileset_improve); //writing file with improved lines
fclose($handle); //closing the opened file
remember this lines will make your search line blank....
if you wanna then you can arrange whole array i.e. shifting following indexed data to previous index to decrease line counts but this will increase your programming complexity.
Hope this will work for you.
Thanks
Use PHP_EOL on your explode function instead of "\n". PHP_EOL will handle the correct line break character(s) of the server platform.

How to extract data from CSV with PHP

I'm using the Sebastian Bergmann PHPUnit selenium webdriver.
Current I have:
$csv = file_get_contents('functions.csv', NULL,NULL,1);
var_dump($csv);
// select 1 random line here
This will load my CSV file and give me all possible data from the file.
It has multiple rows for example:
Xenoloog-FUNC/8_4980
Xylofonist-FUNC/8_4981
IJscoman-FUNC/8_4982
Question: How can I get that data randomly?
I just want to use 1 ( random) line of data.
Would it be easier to just grab 1 (random) line of the file instead of everything?
Split the string into an array, then grab a random index from that array:
$lines = explode("\n", $csv);
$item = $lines[array_rand($lines)];
You could use the offset and maxlen parameters to grab part of the file using file_get_contents. You could also use fseek after fopen to select part of a file. These functions both take numbers of bytes as arguments. This post has a little more information:
Get part of a file by byte number in php
It may require some hacking to translate a particular row-index of a CSV file to a byte offset. You might need to generate and load a small meta-data file which contains a list of bytes-occupancies for each row of of CSV data. That would probably help.

Processing structured data into a database from a giant text file using PHP?

I have text files containing structured data (it is a proprietary format and not something simple or common like CSV). I'm trying to put this data into a database. The text files are as large as 50GB so it's impossible for me to read the entire file into memory, extract it into an array, then process it into the database.
The text files are structured in such a way that data on a particular "item" (a specific id in the database) can have multiple lines (new lines) of information in the text file. Items in the text file always start with a line that begins with '01' and can have an infinite number of additional lines (all one after the other), that will all start with 02 or 03 ... up to 08. A new item begins when a new line starts with 01.
01some_data_about_the_first_item
02some_more_data_about_the_first_item
05more_data_about_the_first_item
01the_first_line_of_the_second_item
I'd like to use PHP to process this data.
How can I load a piece of this text file into memory where I can analyze it, get all the lines for an item, and then process it? Is there a way to load all lines up to the next line that starts with 01, process that data, then begin the next scan of the text file at the end of the last scan?
Processing the data once I've loaded pieces of it into memory is not the problem.
Sure. Since you tagged the question with csv, I'll assume you have a CSV file. In that case, fgetcsv is a good function to use, which get one line from the file at a time. Using that you can get as many lines as you need for one record, then process it, then continue with the next one. Rough mockup:
$fh = fopen('file.csv', 'r');
$record = array();
do {
$line = fgetcsv($fh);
if ($line && $line[0] != '01') {
// any line that does not start with 01 is part of the current record,
// adjust condition as necessary
$record[] = $line;
} else if ($record) {
/* put current $record into database */
// start next record
$record = array($line);
}
} while ($line);
Here is a start:
<?php
$fp=fopen('big.txt','r');
while($line=fgets($fp)){
$number=substr($line,0,2);
$data=substr($line,2);
// proccess each line
echo $number.' - '.$data;
}
fclose($fp);
?>

Categories