MDL-72035 csvlib: Write BOM for Excel

Add option to class csv_export_writer to prefix CSV file with UTF-8 byte
order mark (BOM).  This helps Microsoft Excel detect the file's character
encoding.
This commit is contained in:
Leon Stringer
2021-06-30 15:01:11 +01:00
parent 911f9adccf
commit 3236bae2ed
3 changed files with 15 additions and 3 deletions
+11 -1
View File
@@ -390,6 +390,10 @@ class csv_export_writer {
* @var string $path The directory path for storing the temporary csv file.
*/
var $path;
/**
* @var boolean $bom If true prefix file with byte order mark (BOM).
*/
private $bom = false;
/**
* @var resource $fp File pointer for the csv file.
*/
@@ -401,8 +405,9 @@ class csv_export_writer {
* @param string $delimiter The name of the character used to seperate fields. Supported types(comma, tab, semicolon, colon, cfg)
* @param string $enclosure The character used for determining the enclosures.
* @param string $mimetype Mime type of the file that we are exporting.
* @param boolean $bom If true, prefix file with byte order mark.
*/
public function __construct($delimiter = 'comma', $enclosure = '"', $mimetype = 'application/download') {
public function __construct($delimiter = 'comma', $enclosure = '"', $mimetype = 'application/download', $bom = false) {
$this->delimiter = $delimiter;
// Check that the enclosure is a single character.
if (strlen($enclosure) == 1) {
@@ -412,6 +417,7 @@ class csv_export_writer {
}
$this->filename = "Moodle-data-export.csv";
$this->mimetype = $mimetype;
$this->bom = $bom;
}
/**
@@ -437,6 +443,10 @@ class csv_export_writer {
if(!isset($this->path)) {
$this->set_temp_file_path();
$this->fp = fopen($this->path, 'w+');
if ($this->bom) {
fputs($this->fp, core_text::UTF8_BOM);
}
}
$delimiter = csv_import_reader::get_delimiter($this->delimiter);
fputcsv($this->fp, $row, $delimiter, $this->csvenclosure);