PHP格式化csv上传脚本中的列(美元符号)


PHP Formatting A Column (dollar sign) In csv Upload Script

我有一个脚本,可以上传一个包含3列(电话、姓名、金额)的csv文件。这个脚本删除了手机上的任何格式;()-并将文件放到服务器上。文件中的金额列显示了类似125.00的金额,我需要它显示125.00美元。任何帮助都将不胜感激。

$file_destination = '/****/****/****/***/' . $file_name_new;
$contents = file_get_contents($file_tmp);
$contents = str_replace("(","",$contents);
$contents = str_replace(")","",$contents);
$contents = str_replace("-","",$contents);
file_put_contents($file_tmp, $contents);
if(move_uploaded_file($file_tmp, $file_destination)) {

无论您是想严格重新格式化值以进行输出,还是想将新格式化的数据存储在CSV文件中,使用fgetcsvfputcsv可能会更有效。这些功能是为正确读取和写入CSV格式的文件而设计的。

示例

$rows = [];
if (($handle = fopen($file_tmp, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        list($phone, $name, $amount) = $data;
        $phone = str_replace(['(',')','-'], '', $phone);
        $amount = sprintf('$%.2f', $amount);
        // you can build a new array with the updated values
        $rows[] = [$phone, $name, $amount];
        // or output directly
        echo "$phone | $name | $amount";
    }
    fclose($handle);
}
// if you want to save the destination with the updated information...
$fp = fopen($file_destination, 'w');
foreach ($rows as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);