我有一个模板CSV文件,它有像{$NAME}这样的占位符,现在我想用实际值替换所有这些占位符。
我用的是拉拉维尔,但这不重要。
目前正在做这样的事情:
$templateCSV = Storage::get('quote.intake.form.template.csv'); // it reads the file contents
$vars = [ // define the placeholders with actual values
'{$AGENT_NAME}' => $agent['name'],
'{$AGENT_PHONE}' => $agent['phone'],
];
$newCSV = strtr($templateCSV, $vars); // finally replace those placeholders.
Storage::put("my-new-csv.csv", $newCSV); // saves the new CSV这很管用,但我不认为这是正确的方法。因为当一个值有",“它将破坏csv结构。
我相信一定有更好的方法。
提前谢谢你。
发布于 2022-09-05 07:40:15
可以将值包装为双引号,但这意味着需要在值中转义双引号:
$sanitiseCsv = fn ($value) => '"'.str_replace('"', '""', $value).'"';
$vars = [ // define the placeholders with actual values
'{$AGENT_NAME}' => $sanitiseCsv($agent['name']),
'{$AGENT_PHONE}' => $sanitiseCsv($agent['phone']),
];注:加倍双引号似乎是正确的方法,以避免双引号在双引号的CSV值。
https://stackoverflow.com/questions/73605724
复制相似问题