PHP implements replacement of placeholders in CSV files with actual values
P粉520204081
P粉520204081 2023-09-16 11:51:32
0
1
992

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粉520204081
P粉520204081

reply all(1)
P粉652495194

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template