【问题标题】:How to export a tab-separated txt file from php array without quotes如何从不带引号的php数组中导出制表符分隔的txt文件
【发布时间】:2015-04-06 19:23:14
【问题描述】:

我已经成功地使用下面的代码为产品 Feed 保存了一个制表符分隔的文件。但是,我提交的提要要求字段不包含在引号中。有没有办法在字段中不带引号保存此文件。

$feed[]=array('Item','Description','Category');
$feed[]=array('1-1','Words describing item 1, for example.','Top Category > SubCategory1');
$feed[]=array('1-2','Words describing item 2.','Top Category > SubCategory2');

header('Content-type: text/tab-separated-values');
header("Content-Disposition: attachment;filename=bingproductfeed.txt");
$f  =   fopen('php://output', 'a');
foreach ($feed as $fields) {
    //$fields=str_replace('"','',$fields);
    //$fields=trim($fields,'"');
    fputcsv($f, $fields, "\t");
}

//Outputs:
//Item  Description Category
//1-1   "Words describing item 1, for example." "Top Category > SubCategory1"
//1-2   "Words describing item 2."  "Top Category > SubCategory2"

//I need:
//Item  Description Category
//1-1   Words describing item 1, for example.   Top Category > SubCategory1
//1-2   Words describing item 2.    Top Category > SubCategory2

我尝试将引号剪掉并用空格替换它们,但没有运气。有没有办法做到这一点,以便我可以毫无错误地提交此提要?

【问题讨论】:

标签: php tsv fputcsv


【解决方案1】:

基于PHP manual,我想说您可以省略 fopen 行,直接在页面上回显您的输出。

php://输出¶

php://output 是一个只写流,它允许您以与 print 和 echo 相同的方式写入输出缓冲区机制。

所以是这样的:

$feed[]=array('Item','Description','Category');
$feed[]=array('1-1','Words describing item 1, for example.','Top Category > SubCategory1');
$feed[]=array('1-2','Words describing item 2.','Top Category > SubCategory2');

header('Content-type: text/tab-separated-values');
header("Content-Disposition: attachment;filename=bingproductfeed.txt");
foreach ($feed as $fields) {
    //$fields=str_replace('"','',$fields);
    //$fields=trim($fields,'"');
    echo implode("\t",$fields);
}

【讨论】:

  • 我使用了类似的方法,因为 PHP 的内置 CSV 函数在尝试使用制表符作为分隔符时会出现错误。我建议作为一项附加安全功能的一件事是确保字段数据中永远不会留下任何选项卡,这会使事情变得混乱。所以类似于循环数据,str_replace("\t", ' ', $field) 或类似的东西。
猜你喜欢
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 2011-01-17
  • 2011-09-26
相关资源
最近更新 更多