remove new line from txt file after insert value - php

i create a txt file from a folder in that way:
$fp = fopen("mylist.txt","rw+");
foreach(glob("folder/*.*") as $value){
fwrite($fp,$value."\n");
}
and it create inside the txt each items, one per line, BUT it also add a newline at the end of the file.
This is the content of mylist.txt:
foldelr/file1.mp3
folder/file2.mp3
(BLANK NEWLINE)
I tried to remove the blank newline at the end of the txt file, in this way:
$filetxt = fopen("mylist.txt","r");
$rtrim = rtrim($filetxt, "\n");
$newfile = file_put_contents("newfile.txt", $rtrim);
But it doesn't work, because in the "newfile.txt", i still have the newline blank after last file name.
I tried to convert file in array, use "array_diff()" to remove the last line, but it fail.
I tried also all the suggestions in this thread: remove new line characters from txt file using php but not fix my problem.
Does anyone can please help me to understand what i'm missing or mistaken?
Kind Regards
Brus

Use file_get_contents method it works fine for me
$fp = fopen("mylist.txt","rw+");
foreach (glob("test/*.*") as $value) {
fwrite($fp, $value . "\n");
}
$filetxt = file_get_contents("mylist.txt");
$rtrim = rtrim($filetxt, "\n");
$newfile = file_put_contents("mylist.txt", $rtrim);
Or You can also remove the last newline by using the array count.
$fp = fopen("mylist.txt","rw+");
$i =0;
foreach(glob("folder/*.*") as $value){
$i++;
if($i < count(glob("folder/*.*")))
fwrite($fp,$value."\n");
else
fwrite($fp,$value);
}

Have you tried to first write new line and only than value (assuming you already have content in file)?
fp = fopen("mylist.txt","rw+");
foreach(glob("folder/*.*") as $value){
fwrite($fp, "\n".$value);
}

Related

merge csv files using PHP

I have a .csv file which I can use with Google maps API to successfully create map data.
What I'm looking to do is merge 2 (or more) .csv files and display the TOTAL data on the Google map in the same way. They are all in the same format.
I have the paths to the 2 csv files and if need be, a blank .csv file in the same directory where the files could be merged to...
Unfortuantely, the .csv files all have an initial 'header row' which would be awesome to omit when merging...
If anyone can point me in the right direction, I'd be very happy. Thanks
edit: I've tried:
$data1 = file_get_contents('google_map_data.csv');
$data2 = file_get_contents('google_map_data2.csv');
$TOTALdata = "google_map_dataALL.csv";
function joinFiles(array $files, $result)
{
if(!is_array($files)) {
throw new Exception('`$files` must be an array');
}
$wH = fopen($result, "w+");
foreach($files as $file)
{
$fh = fopen($file, "r");
while(!feof($fh))
{
fwrite($wH, fgets($fh));
}
fclose($fh);
unset($fh);
fwrite($wH, "\n"); //usually last line doesn't have a newline
}
fclose($wH);
unset($wH);
joinFiles(array($data1, $data2), $TOTALdata);
I'm assuming both files are small, so loading them all in one go should be OK.
The code loads both files then removes the first line off the second one. It also removes any end of line from the first file, but adds it's own to ensure it always has a new line...
$data1 = file_get_contents('google_map_data.csv');
$data2 = file_get_contents('google_map_data2.csv');
$TOTALdata = "google_map_dataALL.csv";
$data2 = ltrim(strstr($data2, PHP_EOL));
file_put_contents($TOTALdata, rtrim($data1).PHP_EOL.$data2);

How to change all values in a column of a csv file to a specific value php

I have a csv file that looks something like this (there are many more rows):
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
What I want to do is to change all the values in the fourth column,456,343 to 500.
I'm new to php and am not sure how to do this.
I have tried
<?php
$file = fopen('myfile.csv', 'r+');
$toBoot = array();
while ($data = fgetcsv($file)) {
echo $data[3];
$data[3] = str_replace($data[3],'500');
array_push($toBoot, $data);
}
//print_r($toBoot);
echo $toBoot[0][3];
fputcsv($file, $toBoot);
fclose($file)
?>
But it prints
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
Array,Array
not
Jim,jim#email.com,8882,500
Bob,bob#email.com,8882,500
I've looked at this post, PHP replace data only in one column of csv but it doesn't seem to work.
Any help appreciated. Thanks
You can use preg_replace and replace all values at once and not loop each line of the CSV file.
Two lines of code is all that is needed.
$csv = file_get_contents($path);
file_put_contents($path, preg_replace("/(.*),\d+/", "$1,500", $csv));
Where $path is the path and to the CSV file.
You can see it in action here: https://3v4l.org/Mc3Pm
A quick and dirty way to way to solve your problem would be:
foreach (file("old_file.csv") as $line)
{
$new_line = preg_replace('/^(.*),[\d]+/', "$1,500", $line);
file_put_contents("new_file.csv", $new_line, FILE_APPEND);
}
To change one field of the CSV, just assign to that array element, you don't need to use any kind of replace function.
$data[3] = "500";
fputcsv() is used to write one line to a CSV file, not the entire file at once. You need to call it in a loop. You also need to go back to the beginning of the file and remove the old contents.
fseek($file, 0);
ftruncate($file, 0);
foreach ($toBoot as $row) {
fputcsv($file, $row);
}

PHP - Adding line to textfile overwrites old lines.Also weird s: characters in textfile?

What is the best way for adding a line to a textfile? When I run the below code, it overwrites all lines.
Also when adding a line it contains some "s:4:" & s:60: characters. What does this mean? I just want to add the $photourl to urls.txt.
<?php
foreach ($_POST['photoselect'] as $photourl) {
file_put_contents($target_dir . '/urls.txt', $photourl);
$fp = fopen($target_dir . '/urls.txt','w');
fwrite($fp,serialize($photourl));
}
?>
You can append with file_put_contents
file_put_contents($target_dir . '/urls.txt', $photourl, FILE_APPEND);
When opening a file, the last parameter indicates how you want the file pointer to be set. With 'w', this truncates the file, you probably want to have 'a' which means put the pointer at the end of the file. ( see http://php.net/manual/en/function.fopen.php modes )
Unless you content contains special characters, just write it and not serialize it.
Your code also overwrites the file each time...
$fp = fopen($target_dir . '/urls.txt','a');
foreach ($_POST['photoselect'] as $photourl) {
fwrite($fp,$photourl.PHP_EOL);
}
fclose($fp);

Format txt file

I need to import csv file with php getcsv function but the file is not well formated and cannot import it. After uploading the file, I'd like to delete all " inside the file to have a proper file with ; for each field.
This is an example of my file:
"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
"M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email#gmail.com;010000000"
"M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email#gmail.com;060000000"
"M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email#gmail.com;070000000"
I think I would need to read each line of the file,and maybe use str_replace but I don't know how to write the new file...
Assuming you can get your code into a text string, you can just replace/remove the double-quotes. Then parse the text and get it into a format that will support fputcsv().
When writing the folder, be sure to check that your user has permissions to write to this folder (for example if the parent folder has permissions drwxr-xr-x, you can fix it with chmod g+w folder_name).
<?php
// sample text to parse
$some_text = '"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
"M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email#gmail.com;010000000"
"M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email#gmail.com;060000000"
"M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email#gmail.com;070000000"';
// remove quotes
$final_text = str_replace('"', '', $some_text);
// create array of rows by searching for new lines
$data = str_getcsv($final_text, "\n");
// create an empty array to save our final csv data
$final_csv = array();
// loop thru the array and save to the final csv data
foreach ($data as $value) {
// before saving to final csv data, split row into individual column items
$value_array = explode(";", $value);
$final_csv[] = $value_array;
}
// helper debugger to show data before writing it
echo "<pre>";
print_r($final_csv);
echo "</pre>";
// create a new file for writing or open and truncate to 0
$fp = fopen('file.csv', 'w');
// write to file from final csv data
foreach ($final_csv as $fields) {
fputcsv($fp, $fields);
}
// close file
fclose($fp);
?>

Copy Multiple Images From Remote Server

I am trying to copy multiple images from a remote host (using a URL) to my local box (using XAMPP on my local box to execute the script).
I am using copy(). When I go to execute the copy(), only the LAST image in the array is created. So, if I have 5 image links, only the 5th image gets created and nothing prior even gets a file created.
I have tried CURL and FOpen and then both create all of the files, but all of the files are blank except, again, the last file which is perfectly fine.
$txt_file = file_get_contents('urls_for_images.txt');
if(!empty($txt_file)){
$image_links = explode("\n", $txt_file);
$i = 1;
foreach($image_links as $image_link){
$file_info = pathinfo($image_link);
copy($image_link, 'images/00' . $i . '_original.' . $file_info['extension']);
$i++;
}
}
I am not sure where the problem is occurring, but it seems odd to me that it will copy the last image in the text file, but not any of the others.
Thanks for the help in advance!
The i variable never changes, therefore the code tries to copy a file with the same name over and over again and only the last file is saved.
Try modifying your code this way:
$txt_file = file_get_contents('urls_for_images.txt');
if(!empty($txt_file)){
$image_links = explode("\n", $txt_file);
$i = 1;
foreach($image_links as $image_link){
$file_info = pathinfo($image_link);
copy($image_link, 'images/00' . $i . '_original.' . $file_info['extension']);
$i++;
}
}
You'd be better off with just file(), which reads the file into an array automatically:
$files = file('urls_for_images.txt', FILE_IGNORE_NEW_LINES);
foreach($files as $remote_file) {
$local_file = ....;
copy($remote_file, $local_file);
}
It appears the problem is the text file which line endings are \r\n and you are exploding with only \n. The quickest way to fix this is either explode by \r\n; or trim with default parameters to remove \r from the end of each line.
foreach($image_links as $image_link){
$image_link = trim($image_link);
$file_info = pathinfo($image_link);
...
}
However, the cleanest way to do this is to use file function, which handles line endings automatically. I recommend you to use this approach.

Categories