doujiong2533 2014-04-29 01:08
浏览 62
已采纳

php导出到csv期间删除空格

I'm having trouble with my php script to trim the whitespace from within values as i output the results of a query from postgresql. the commented line is the returned array from a print_r();

<?php

$db = pg_connect("host=localhost dbname=test user=test password=test");
$result = pg_query($db, "SELECT * FROM table WHERE field = 'test'");
$array = pg_fetch_all($result);

//Array ( [0] => Array ( [id_number] => 214 [country] => Zanzibar [sector] => Unguja [site] => Chumbe Island Coral Park (CHICOP) [username] => n ) [1] => Array ( [id_number] => 213 [country] => Zanzibar [sector] => Unguja [site] => Chumbe Island Coral Park (CHICOP) [username] => n )

//*************
$array_explode = explode(",", $array);
$array_trimmed = array_map("trim", $array_explode);
$array_implode = implode(",", $array_trimmed);
unset($array_explode);
//*************

$fp = fopen('file.csv', 'w');

foreach ($array_implode as $fields) {

fputcsv($fp, $fields);
}
fclose($fp);


?>

If i remove the lines between the stars then the csv outputs (just with a whole lot of unnecessary whitespace. I have tried both with and without the implode(). this has been driving me up the wall and any help would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • douren2395 2014-04-29 05:54
    关注

    I was able to get it to work using your code:

    <?php
    $array = Array (0 => Array ( 'id_number' => 214, 'country' => 'Zanzibar', 'sector' => 'Unguja', 'site' => 'Chumbe Island Coral Park (CHICOP)', 'username' => 'n'),
            1 => Array ( 'id_number' => 213, 'country' => 'Zanzibar', 'sector' => 'Unguja', 'site' => 'Chumbe Island Coral Park (CHICOP)', 'username' => 'n'));
    
    $fp = fopen('file.csv', 'w');
    foreach ($array as $fields) {
            $array_trimmed = array_map("trim", $fields);
            fputcsv($fp, $array_trimmed);
    }
    fclose($fp);
    

    output from file.csv:

    214,Zanzibar,Unguja,"Chumbe Island Coral Park (CHICOP)",n
    213,Zanzibar,Unguja,"Chumbe Island Coral Park (CHICOP)",n
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。