有一个功能可以完美地将数据写入文件并即时保存。唯一的问题是,当我尝试resultArray
通过 fputcsv 格式化数据时,它无法执行此操作并返回:
*** 的网页可能暂时不可用或永久移至新地址
但是,对于更简单的数组,selectedColumn
一切正常。下面是代码和resultArray
. 我不明白为什么会这样。也许数组没有正确组合并且因此无法格式化?
编码:
function checkEmptyField($field)
{
if(empty($field))
{
return '-';
}else
{
return $field;
}
}
$nameFile = 'keywords.csv';
$handle = fopen("php://output", "w");
header('Content-disposition: attachment; filename='.$nameFile);
header('Content-Type: text/csv; charset=UTF-8');
// Create head of table
$selectedColumn = [];
foreach ($clientColumns as $key=>$val)
{
if($val == 1)
{
$selectedColumn [] = $key;
}
}
// Create body of table
$resultArray = [$selectedColumn];
foreach ($keywordsCharacteristic as $fields)
{
$tempRow = [];
foreach ($selectedColumn as $column)
{
switch ($column) {
case "features":
$tempRow [] = $fields['serpFeatures'];
break;
case "position":
$tempRow [] = checkEmptyField($fields['position']);
break;
case "traffic":
$tempRow [] = checkEmptyField($fields['traffic']);
break;
case "volume":
$tempRow [] = checkEmptyField($fields['volume']);
break;
case "CPC":
$tempRow [] = checkEmptyField($fields['cpc']);
break;
case "url":
$tempRow [] = checkEmptyField($fields['pageUrl']);
break;
case "checked":
$tempRow [] = checkEmptyField($fields['checked']);
break;
}
}
$resultArray [] = $tempRow;
}
var_dump($resultArray);
//fputcsv($handle, $resultArray);
fclose($handle);
exit();
关于resultArray
. 即使我删除了 对应的字段features
,也不会有结果,尽管数组将变得与文档中的示例相同,只是更大。
字段匹配
features
:
[0]=> array(2) { [0]=> array(3) { ["key"]=> string(7) "reviews" ["img"]=> string(11) "reviews.png" ["name"]=> string(7) "Reviews" } [1]=> array(3) { ["key"]=> string(15) "relatedSearches" ["img"]=> string(12) "Searches.png" ["name"]=> string(16) "Related Searches" } }
array(3) {
[0]=>
array(7) {
[0]=>
string(8) "features"
[1]=>
string(8) "position"
[2]=>
string(7) "traffic"
[3]=>
string(6) "volume"
[4]=>
string(3) "CPC"
[5]=>
string(3) "url"
[6]=>
string(7) "checked"
}
[1]=>
array(7) {
[0]=>
array(2) {
[0]=>
array(3) {
["key"]=>
string(7) "reviews"
["img"]=>
string(11) "reviews.png"
["name"]=>
string(7) "Reviews"
}
[1]=>
array(3) {
["key"]=>
string(15) "relatedSearches"
["img"]=>
string(12) "Searches.png"
["name"]=>
string(16) "Related Searches"
}
}
[1]=>
string(1) "-"
[2]=>
string(1) "-"
[3]=>
string(1) "-"
[4]=>
string(1) "-"
[5]=>
string(1) "-"
[6]=>
string(10) "2022-02-07"
}
[2]=>
array(7) {
[0]=>
array(3) {
[0]=>
array(3) {
["key"]=>
string(7) "reviews"
["img"]=>
string(11) "reviews.png"
["name"]=>
string(7) "Reviews"
}
[1]=>
array(3) {
["key"]=>
string(5) "tweet"
["img"]=>
string(9) "tweet.png"
["name"]=>
string(5) "Tweet"
}
[2]=>
array(3) {
["key"]=>
string(15) "relatedSearches"
["img"]=>
string(46) "Searches.png"
["name"]=>
string(16) "Related Searches"
}
}
[1]=>
string(1) "3"
[2]=>
string(1) "-"
[3]=>
string(1) "-"
[4]=>
string(1) "-"
[5]=>
string(1) "-"
[6]=>
string(10) "2022-02-07"
}
}
已解决 原因是我没有
resultArray
通过foreach,而是将数组作为元素传递,而不是逐元素表示法。我用features
array_merge解决了这个问题。生成的代码如下所示: