我有一个像这样的数组
Array
(
[0] => Array
(
[0] => 204-7523179-7900317-A4WhiteFramedPrint
[1] => A4 White Framed Print
[2] => 21M
[3] => Daddy
[4] => Love Kieran & Mason Xxx
)
[1] => Array
(
[0] => 204-7523179-7900317-A4WhiteFramedPrint
[1] => A4 Black Framed Print
[2] => 21M
[3] => Mummy
[4] => Love Bob Xxx
)
}
我正在尝试将其导出到Tab分隔文件(TSV),我使用
header('Content-type: text/tab-separated-values');
header("Content-Disposition: attachment;filename=file.txt");
foreach ($array as $fields) {
echo implode("\t",$fields);
}
这很好用并使用制表符分隔数组值,但是没有新行,第一个数组的值显示在txt文件中,然后是一个长空格,后跟下一个数组' s值(在同一行)。
如果可能的话,我希望将每个数组放在文本文件中的新行上,我尝试添加echo "\n"
或PHP_EOL
等,但这些都不起作用。
感谢任何帮助。
答案 0 :(得分:0)
您需要使用\n
$array = [
[
'204-7523179-7900317-A4WhiteFramedPrint',
'A4 White Framed Print',
'21M',
'Daddy',
'Love Kieran & Mason Xxx',
], [
'A4 White Framed Print',
'21M',
'Mummy',
'Love Bob Xxx',
]
];
foreach ($array as $key => $fields) {
$array[$key] = implode("\t",$fields);
}
echo implode("\n", $array);
答案 1 :(得分:0)
尝试在每次implode
通话后添加换行符!
<?php
$array = [
[
'A4 White Framed Print',
'21M',
'Daddy',
'Love Kieran & Mason Xxx',
],
[
'A4 White Framed Print',
'21M',
'Mummy',
'Love Bob Xxx',
]
];
foreach ($array as $subArray) {
echo implode("\t", $subArray);
echo "\n";
}
答案 2 :(得分:0)
这可能会对你有所帮助。
使用您的示例:
<?php
$array = array(
array('204-7523179-7900317-A4WhiteFramedPrint', 'A4 White Framed Print', '21M', 'Daddy','Love Kieran & Mason Xxx'),
array('204-7523179-7900317-A4WhiteFramedPrint','A4 Black Framed Print','21M','Mummy','Love Bob Xxx')
);
header('Content-type: text/tab-separated-values');
header("Content-Disposition: attachment;filename=file.txt");
foreach ($array as $fields) {
echo implode("\t",$fields).PHP_EOL;
}
?>
使用生成的文件:
<?php
$array = array(
array('204-7523179-7900317-A4WhiteFramedPrint', 'A4 White Framed Print', '21M', 'Daddy','Love Kieran & Mason Xxx'),
array('204-7523179-7900317-A4WhiteFramedPrint','A4 Black Framed Print','21M','Mummy','Love Bob Xxx')
);
$filename = 'csv-file.txt';
$file = fopen($filename, "w");
foreach ($array as $fields) {
fwrite($file, implode("\t",$fields).PHP_EOL);
}
fclose($file);
header('Content-Description: File Transfer');
header('Content-type: text/tab-separated-values');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
?>
在Apache 2.2(Windows 10)和IIS 10(Windows 10)上测试。