par
Saian » 05 mai 2023, 16:39
Un exemple de code plus complet. La fonction validateLine peut être modifiée selon la condition souhaitée.
<?php
/* open the file */
if (($handle = fopen('test.csv', 'rb')) === false) {
echo 'error while opening the file';
exit;
}
$length = 1024;// 1 ko, increase if lines longer
$separator = ';';// adapt to csv format
$enclosure = '"';// adapt to csv format
/* skip the first line (header) */
fgetcsv($handle, $length, $separator, $enclosure);
/* loop over the rest of the file */
while (($data = fgetcsv($handle, $length, $separator, $enclosure)) !== false) {
/* skip the line if not valid */
if (validateLine($data) === false) {
continue;
}
/* do something with $data */
echo implode(';', $data) . '<br/>';
}
/* close the file */
fclose($handle);
/* function to validate the line */
function validateLine($data): bool
{
/* let's say we keep the line if at least 80% of the columns are filled */
$successRate = 0.8;// 0 to 1 for 0% to 100%
$colsNumber = count($data);
$colsFilled = 0;
foreach ($data as $value) {
if (!empty($value)) {
++$colsFilled;
}
}
return $colsFilled / $colsNumber >= $successRate;
}
Un exemple de code plus complet. La fonction validateLine peut être modifiée selon la condition souhaitée.
[PHP]<?php
/* open the file */
if (($handle = fopen('test.csv', 'rb')) === false) {
echo 'error while opening the file';
exit;
}
$length = 1024;// 1 ko, increase if lines longer
$separator = ';';// adapt to csv format
$enclosure = '"';// adapt to csv format
/* skip the first line (header) */
fgetcsv($handle, $length, $separator, $enclosure);
/* loop over the rest of the file */
while (($data = fgetcsv($handle, $length, $separator, $enclosure)) !== false) {
/* skip the line if not valid */
if (validateLine($data) === false) {
continue;
}
/* do something with $data */
echo implode(';', $data) . '<br/>';
}
/* close the file */
fclose($handle);
/* function to validate the line */
function validateLine($data): bool
{
/* let's say we keep the line if at least 80% of the columns are filled */
$successRate = 0.8;// 0 to 1 for 0% to 100%
$colsNumber = count($data);
$colsFilled = 0;
foreach ($data as $value) {
if (!empty($value)) {
++$colsFilled;
}
}
return $colsFilled / $colsNumber >= $successRate;
}
[/PHP]