N
N
Nik_10112021-07-07 10:47:52
PHP
Nik_1011, 2021-07-07 10:47:52

How to output csv file to utf-8 using iconv?

Hello.

There is a csv file in windows-1251 encoding. I tried 2 options for converting to utf-8:

<?php

$row = 1;
if (($handle = fopen("111.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo iconv("UTF-8", "Windows-1251", $data[$c]) . "<br />\n";
    }
  }
  fclose($handle);
}

60e55bee72899958474270.png

<?php
header('Content-Type: text/html; charset=UTF-8');

$row = 1;
if (($handle = fopen("111.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
    $data = array_map("utf8_encode", $data);
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
  }
  fclose($handle);
}

60e55bfbcc129086958050.png

How to do better?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nik_1011, 2021-07-08
@Nik_1011

Solution
1) Convert to UTF-8 (without BOM) in Notepad++
2) Given code

$row = 1;
if (($handle = fopen("1114.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
  }
  fclose($handle);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question