PHP fwrite() , could not fill txt - php

after code execute my file look like this:
1.info
2.
3.info
4.
5.info
....
I tried with different mode in fopen but still the same.
<?php
$file = 'data.txt';
$lines = file($file);
$newArr = array();
$f = fopen($file,'r+');
foreach($lines as $value){
$newArr[] = $value;
}
unset($newArr[$_GET['id']-1]);
foreach($newArr as $vv){
fwrite($f, $vv.PHP_EOL);
}
fclose($f);
?>

It appears that this is the same and should work:
$file = 'data.txt';
$lines = file($file, FILE_SKIP_EMPTY_LINES);
unset($lines[$_GET['id']-1]);
file_put_contents($file, $lines);
For whatever reason using fwrite():
$file = 'data.txt';
$lines = file($file, FILE_SKIP_EMPTY_LINES);
unset($lines[$_GET['id']-1]);
$f = fopen($file, 'w');
fwrite($f, implode($lines));
/*
foreach($lines as $vv) {
fwrite($f, $vv);
}
*/

Related

fopen is duplicating the same line

I have a file that looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]||55.183.567
I made a function that when executed adds a given number or removes it if already present, which is $added and equals 100 for this example. This is my code:
$added = $_GET['added']; //100 for this example
$f = fopen($file, "w");
$list = file($file);
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
foreach ($details as $key => $value) {
if ($key == 5) {
$newline .= str_replace("[" . $added . "]", "", $value);
} else {
$newline .= $value . "||";
}
}
$line = $newline . "\n";
}
fputs($f, $line);
}
fclose($f);
}
this code is supposed to remove the [100] from the Rocky line since its already present which it kinda does. However, upon further execution instead of adding it back it duplicates the Rocky line and messes it up so the file looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]55.183.567
3||Rocky||21||male||USA||[100][200]55.183.567
||
||
why is it doing this? I cant make any sense out of it...
Thank you.
First, you should read the file before you open it for output, because opening with the w mode truncates the file.
Second, you don't need to loop over the fields in $details if you just want to change one of them. Just access and assign it by index.
Then you can put the line back together with implode().
$list = file($file);
$f = fopen($file, "w");
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
if (strpos("[$added]", $details[5]) === false) {
$details[5] = "[$added]" . $details[5];
} else {
$details[5] = str_replace("[$added]", "", $details[5]);
}
$line = implode('||', $details)
}
fputs($f, $line);
}
fclose($f);

Problem in writing data to CSV file using PHP

I have a problem on writing the data to a csv file using php. It doesn't show any error, but it didn't create the file. Can anyone help me with this?
<?php
$mdarray = array();
$filename = basename(__FILE__, ".php");
$f = fopen("FILES/MonitorStatus.csv", "r");
while (($line = fgetcsv($f)) !== false) {
array_push($mdarray, $line);
}
fclose($f);
foreach ($mdarray as $key => $row) {
$Status[$key] = $row[3];
}
array_multisort($Status, SORT_ASC, $mdarray);
foreach ($mdarray as $line) {
$fp = fopen('file.csv', 'wb');
foreach ($line as $cell) {
fputcsv($fp, $cell);
}
fclose($fp);
}
?>

explode text file into array depend on comma

I'd like to convert my text.tx into array depend on only comma for example:
if I have this text:
so what I need to execute my array like that:
please check my code, my code not work well because it's depend on comma and newline:
<?php
$lines = file ("text.txt");
foreach($lines as $line) {
$data[] = explode(',', $line);
}
?>
<pre>
<?php
print_r($data);
?>
</pre>
$handle = fopen("text.txt", "r");
if ($handle) {
$data = [];
while (($line = fgets($handle)) !== false) {
$data[] = explode(',', $line);
}
fclose($handle);
echo "<pre>";
print_r($data);
} else {
// error opening the file.
}

Remove blank from text file

I want to remove blank line from this text file :
test1
test2
test3
test4
So I try this code in PHP :
$file = __DIR__.$namefile;
foreach ($file as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
But it does not work. Thanks for your help !
How about exploding each new line and checking if it's empty?
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array();
foreach ($lines AS $line) {
if (!empty($line)) {
$result[] = $line;
}
}
$result = implode("\n", $result);
Or, as Henders suggests, look at https://stackoverflow.com/a/7972266/1441858:
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array_filter($lines, 'trim');
$result = implode("\n", $result);
$file = __DIR__.$namefile;
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
if (trim($line) != "") {
$array1[] = $nl;
}
}
fclose($f);
$file = __DIR__.$namefile;
$lines = explode("\n", file_get_contents($file));
$result = array_filter($lines);
echo implode("\n", $result);
file_put_contents($file, implode("\n", $result)); //save
Or use:
$result = array_filter($lines, 'trim');
If there can be whitespaces in blank lines.

from csv to array with end of line chars

To parse CSV files in php im using this function:
private function _csvToArray($url, $delimiter=',')
{
$csvData = file_get_contents($url);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line, $delimiter);
}
return $array;
}
The problem here is Im using EOL to determine where a line ends, if the CSV file have any field with any end of line chars im getting errors.
Example:
Product_Name, "Description"
Product_Name, "Description"
Product_Name, "Description"
Product_Name, "Description"
This works ok, but if I have something like this:
Product_Name, "Description_line_1
Description_line_2"
Product_Name, "Description_line_1
Description_line_2"
Product_Name, "Description_line_1
Description_line_2"
The script will fail, is there any way I can improve the script in order to consider this or is better to use a regular expression to fix first the CSV before calling the sript?
If you want to save writing to a temporary file yourself you can use the memory stream.
private function _csvToArray($url, $delimiter=',')
{
$fp = fopen('php://memory', 'r+');
fwrite($fp, file_get_contents($url));
fseek($fp, 0);
$array = array();
while ($row = fgetcsv($fp, 0, $delimiter)) {
$array[] = $row;
}
fclose($fp);
return $array;
}
fgetcsv can handle EOL in fields if the field data is between enclosure characters.
private function _csvToArray($url, $delimiter=',', $enclosure='"')
{
$handle = fopen($url, 'r');
$array = array();
while($row = fgetcsv($handle, 0, $delimiter, $enclosure))
{
$array[] = $row;
}
fclose($handle);
return $array;
}
Something like this should work (havent properly tested the code):
$csv = array_map('str_getcsv', file($url), ',', '"');
I had an old code lying around which fixed this once for me... But remember... it's from way way back;
$url = 'file.csv';
$csv = array();
$csvContents = file_get_contents($url);
$lines = explode('"'."\n", trim($csvContents));
foreach($lines as $lineNumber => $line) {
$csv[$lineNumber] = array();
$fields = explode(',', $line);
foreach($fields as $field) {
$csv[$lineNumber][] = ltrim(rtrim($field, '"'), '"');
}
}

Categories