【问题标题】:php remove whitespace during export to csvphp 在导出到 csv 期间删除空格
【发布时间】:2014-04-29 01:08:20
【问题描述】:

当我从 postgresql 输出查询结果时,我的 php 脚本无法从值中修剪空格。注释行是从 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()。这一直把我逼到墙上,任何帮助都是非常感谢。

【问题讨论】:

  • 你不应该在数组上使用explodeexplode 用于将字符串拆分为令牌数组
  • @Phil,我使用 explode 来获取数组中的各个值。
  • 那你做错了。恰当命名的$array 已经是一个数组
  • @Phil 有什么建议吗?我在这方面相对较新,并且已经收到了值中有很多空格的数据,对于 400 行 csv,将导出的文件大小增加到 1.5mb
  • 这里是对您有帮助的链接。 stackoverflow.com/questions/21575764/…

标签: php postgresql


【解决方案1】:

我能够使用您的代码使其工作:

<?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

【讨论】:

  • @rmctrazier 感谢您的回复。我也许应该取出注释数组,因为我只是用它来测试(我现在将它取出以防止进一步的混乱)。代码中的$array 值传递了一个值数组,我也会将其编辑到原始代码块中。
  • @rmctrazier 再次感谢您的回复,但问题是,那里没有任何东西可以修剪空白?我很抱歉,因为我认为我输出了唯一没有空格的值!
  • 我更新了我的答案,在写入文件之前将空格修剪到字段中。
猜你喜欢
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多