In the csv file, I have lines with this structure :
Name;timestamp;floatValue
Name;timestamp;floatValue
Name;timestamp;floatValue
...
In my code, I check each value in the line, I filter them,then I want to correct the float value by calling the function floatval
, because I have wrong values sometimes like : .904 or 2,454 and using this function returns the right formatted one.
<?php
if (($handle = fopen('file.csv', "r+")) !== false) {
while (($line = fgetcsv($handle, 1024, ";")) !== false) {
$headers = [
'name',
'timestamp',
'floatValue',
];
$line = array_combine($headers, $line);
$args = array('name' => array('filter' => FILTER_VALIDATE_REGEXP,
'options' => array('regexp' => '/^[a-zA-Z0-9_:.()\/]*$/'), ),
'timestamp' => array('filter' => FILTER_CALLBACK,
'options' => 'validateDate', ),
'floatValue' => array('filter' => FILTER_VALIDATE_FLOAT),);
$result = filter_var_array($line, $args);
$line = correctFloat($line);
print_r($line);
}
}
fclose($handle);
function validateDate($date)
{
if (!preg_match("/^\d{8}$/", substr($date, 0, 8))) {
return false;
}
if (!checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
return false;
}
if (substr($date, 8, 2) > 23 || substr($date, 10, 2) > 59 || substr($date, 12, 2) > 59) {
return false;
}
return true;
}
function correctFloat($line){
$float = $line['floatValue'];
$value = str_replace(",",".",$float);
return str_replace($float,floatval($value),$line);
}
?>
Now I'm stuck how to write the correct value inside the file in the right line?
I tried this:
fwrite($handle,implode(";",correctFloat($line)));
But it didn't work. How to re-write each line into the file in the right position with the correct float without losing data? Any idea?
:::EDIT:::
I also tried to use a temporary file:
$temp = tmpfile();
fputcsv($temp,correctFloat($line),';');
fwrite($handle,fread($temp, 1024));
but I didn't get a good result. nothing happened inside the file.
Example
Input :
Name;timestamp;.23
Name;timestamp;2,4578
Name;timestamp;1.23
Expected output:
Name;timestamp;0.23
Name;timestamp;2.4578
Name;timestamp;1.23
In this example: 2,4578 should be in the output : 2.4578 (I replace the comma with '.' using the function correctFloat($line)
above )
New try:
$newline = correctFloat(array_combine($headers, $line));
array_push($newline,chr(10));
$l = implode(";",$newline);
fwrite($handle,$l);
rewind($handle);
Only the first value changes and then the file is refreshing without getting out of the loop.