I have a template CSV file which contains placeholders like {$NAME}
Now I want to replace all these placeholders with actual values.
I'm using Laravel, but that doesn't matter.
The current approach is as follows:
$templateCSV = Storage::get('quote.intake.form.template.csv'); // 读取文件内容 $vars = [ // 定义占位符和实际值 '{$AGENT_NAME}' => $agent['name'], '{$AGENT_PHONE}' => $agent['phone'], ]; $newCSV = strtr($templateCSV, $vars); // 最后替换这些占位符。 Storage::put("my-new-csv.csv", $newCSV); // 保存新的CSV文件
This works, but I don't think it's the right way to do it because it breaks the CSV structure when a value contains ",".
I'm sure there must be a better way to do this.
Thank you for your help.
P粉6524951942023-09-17 09:57:48
You can wrap the value in double quotes, but this means you need to escape the double quotes inside the value:
$sanitiseCsv = fn ($value) => '"'.str_replace('"', '""', $value).'"'; $vars = [ // 使用实际值定义占位符 '{$AGENT_NAME}' => $sanitiseCsv($agent['name']), '{$AGENT_PHONE}' => $sanitiseCsv($agent['phone']), ];
Note: Doubling double quotes appears to be the correct way to escape double quotes in a CSV value wrapped in double quotes.