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 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python