Created
April 19, 2020 23:49
-
-
Save haxianhe/473e5782f95ec414a0c87fdb5e2a4eae to your computer and use it in GitHub Desktop.
格式化数据写入到文件中, 主要是写csv文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* brief: 格式化数据写入到文件中, 主要是写csv文件 | |
* | |
* @param $arrData //要写入是的数据。二位数组。[['title' => '标题1', 'title2' => '标题2']] | |
* @param $arrTitle //标题,一维数组。定义顺序。和数据的key一致。 | |
* @param $filepath //写入文件路径 | |
* @param $write_type //1: 保留原来数据,往后插入。 2: 保留原来数据,在头部写入. 注意,如果是文件头写入,是覆盖式写入,不是插入式。且从第一行开始. 这个时候就需要预先写入空行,且空行占用字节数应该大于等于要写入头部的字节数。否则会覆盖。 | |
* | |
* @return bool | |
*/ | |
public static function writeFormatCsvFile($arrData, $arrTitle, $filepath, $write_type = self::WRITE_TYPE_APPEND) | |
{ | |
$file = $filepath; | |
if ($write_type == self::WRITE_TYPE_TOP) { | |
$handle = fopen($filepath, 'c'); | |
} | |
if (is_array($arrData)) { | |
foreach ($arrData as $data) { | |
$line = ''; | |
foreach ($arrTitle as $key => $title) { | |
$val = str_replace(array(",", "\n", "\r"), array(",", " ", " "), $data[$key]); | |
$val = str_replace(["\xe2\x80\x8b", "\xe2\x80\x8c", "\xe2\x80\x8d"], ['', '', ''], $val); | |
$line .= $val . ','; | |
} | |
$line .= "\n"; | |
if ($write_type == self::WRITE_TYPE_TOP) { | |
fwrite($handle, $line); | |
} else { | |
file_put_contents($file, $line, FILE_APPEND); | |
} | |
} | |
} | |
if ($write_type == self::WRITE_TYPE_TOP) { | |
fclose($handle); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment