我正在使用我的php脚本来修改值内的空格,因为我从postgresql输出查询结果。注释行是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);
?>
如果我删除了星星之间的线条,那么csv输出(只有很多不必要的空格。我已经尝试过使用implode()
和不使用{{1}}。这已经把我推到了墙上,任何帮助非常感谢。
答案 0 :(得分:0)
我能够使用您的代码使其工作:
<?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);
从file.csv输出:
214,Zanzibar,Unguja,"Chumbe Island Coral Park (CHICOP)",n
213,Zanzibar,Unguja,"Chumbe Island Coral Park (CHICOP)",n