krgm.so-manager-dev.com/app/Services/CsvService.php

73 lines
2.1 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Services;
/**
* CSV入出力サービス
* - UtilsのcsvToArrayラッパー将来のエクスポート共通化
*/
class CsvService
{
/**
* CSV → 配列
*
* @param string $path ファイルパス
* @param string $delimiter 区切り文字
* @return array|false
*/
public function toArray(string $path, string $delimiter = ',')
{
return \App\Utils::csvToArray($path, $delimiter);
}
/**
* 配列 → CSV簡易版
*
* @param string $path 出力パス
* @param array<array-key, array<array-key, string|int|float|null>> $rows 行データ
* @param string $delimiter 区切り文字
*/
public function fromArray(string $path, array $rows, string $delimiter = ','): bool
{
$fp = fopen($path, 'w');
if ($fp === false) return false;
foreach ($rows as $row) {
// null を空文字として扱う
$normalized = array_map(static function ($v) {
return $v === null ? '' : (string) $v;
}, $row);
fputcsv($fp, $normalized, $delimiter);
}
fclose($fp);
return true;
}
/**
* 配列 → CSV文字列メモリ構築
*
* @param array<array-key, array<array-key, string|int|float|null>> $rows 行データ
* @param string $delimiter 区切り文字(デフォルト: カンマ)
* @param bool $withBom 先頭にUTF-8 BOMを付与するか
* @return string CSVテキスト
*/
public function buildCsvString(array $rows, string $delimiter = ',', bool $withBom = true): string
{
$stream = fopen('php://temp', 'r+');
if ($stream === false) {
return '';
}
foreach ($rows as $row) {
$normalized = array_map(static function ($v) {
return $v === null ? '' : (string) $v;
}, $row);
fputcsv($stream, $normalized, $delimiter);
}
rewind($stream);
$csv = stream_get_contents($stream) ?: '';
fclose($stream);
return $withBom ? ("\xEF\xBB\xBF" . $csv) : $csv;
}
}