I'm adding some values to a CSV file with data coming from a query, I need that these data were coded as UTF-8 with CRLF at the end of the line. I tried several examples I found here, but no ones works for me, except to leave the file coded in ANSI mode and then convert it in UTF-8 using Notepad
Here it is the code I used to write the CSV file and a picture of the result.
function letsquery($database, $query)
{
$isOK = true;
$query2 = mysqli_query($database, $query);
if ($query2->num_rows > 0)
{
while ($row = mysqli_fetch_assoc($query2))
{
$array1 = $row;
}
} else {
$isOK = false;
}
if ($isOK)
{
$array1 = arrayInsert($array1, 1, ['', '', '', '', '', '', '']); //add some empty values needed by the CSV
if (count($array1)<9)
array_push($array1, "");
global $fnew;
$eol="\r\n";
if (strlen(trim(implode("", $array1)))>0)
fputcsv($fnew, $array1, ';', '\r\n');
\\ fputcsv($fnew, $array1, ';', $eol); tried also in this way...not working
} else {
header("location: tryagain.php");
}
}
Notepad result:
CodePudding user response:
After several tests I think I found a solution:
function letsquery($database, $query)
{
$isOK = true;
$query2 = mysqli_query($database, $query);
if ($query2->num_rows > 0) {
while ($row = mysqli_fetch_assoc($query2)) {
$array1 = $row;
}
} else {
$isOK = false;
}
if ($isOK){
$array1 = arrayInsert($array1, 1, ['', '', '', '', '', '', '']); //add six empty spaces
if (count($array1)<9)
array_push($array1, "");
global $fnew;
$eol="\r\n";
if (strlen(trim(implode("", $array1)))>0)
fputcsv($fnew, $array1, ';');
fseek($fnew, -1, SEEK_CUR);
fwrite($fnew, $eol); // write out a CR/LF
} else {
header("location: tryagain.php");
}
}
I did some test and it works correctly!