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'); // 讀取文件內(nèi)容 $vars = [ // 定義占位符和實(shí)際值 '{$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.
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 = [ // 使用實(shí)際值定義占位符 '{$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.