导出到php中的csv文件时将数组转换为字符串转换错误

时间:2018-09-05 05:55:37

标签: php

我想将此报告导出为csv格式,但出现错误提示 通知:在 8
行的 /Applications/XAMPP/xamppfiles/htdocs/sts_test/export.php 中,将数组转换为字符串 我不知道我搞砸了什么,但似乎根本不起作用..导出的报告显示了数据,但标题部分抛出了此错误

        <?php
header("Content-type: text/csv");
header("Content-disposition: attachment; filename = report.csv");
ob_start();
include('common.php');
function outputCSV($array){
    $fp = fopen('php://output', 'w');
    fputcsv($fp, $array);
    fclose($fp);
}
function getCSV($array) {
    ob_start();
    outputCSV($array);
    return ob_get_clean();
}
$q = $_POST['q'];
$result = mysql_query($q) or die(mysql_error());
$heading[] = array('Customer ID','Visit Date','Customer Name','Customer Age','Address',
    'Organization','Email','Sector','Status','Landline Number','Mobile Number','Amount','Next Visit',
    'Remarks', 'Relation', 'Relative\'s name', 'Relative\'s age', 'Staff ID', 'Staff Code', 'Referred by', 'Staff Name', 'Branch', 'Region');
while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row;
}
$output = '';
$output .= getCSV($heading);
foreach ($data as $key => $value) {
    if(isset($value['cus_age'])){
        $birthDate = $value['cus_age'];
        $currentDate = date('Y/m/d');
        $age = $currentDate - $birthDate;
        unset($value['cus_age']);
        $value = array_slice($value, 0, 3, true) +
        array("cus_age" => $age) +
        array_slice($value, 3, count($value) - 1, true) ;
    }
    //$new_value = array();
    $new_value[0] = $value['cus_id'];
    $new_value[1] = $value['date'];
    $new_value[2] = $value['cus_name'];
    $new_value[3] = $value['cus_age']; 
    $new_value[4] = $value['address'];
    $new_value[5] = $value['organization'];
    $new_value[6] = ($value['email'] == '') ? 'N/A' : $value['email'];
    $new_value[7] = $value['sector'];
    $new_value[8] = $value['status'];
    $new_value[9] = ($value['landline_number'] == '') ? 'N/A' : $value['landline_number'];
    $new_value[10] = $value['mobile_number'];
    $new_value[11] = $value['amount'];
    $new_value[12] = $value['next_visit'];
    $new_value[13] = ($value['remarks'] == '') ? 'N/A' : $value['remarks'];
    $new_value[14] = $value['relation'];
    $new_value[15] = $value['rel_name'];
    $new_value[16] = $value['rel_age'];
    $new_value[17] = $value['staff_code'];
    $new_value[18] = $value['staff_id'];
    $new_value[19] = $value['referred_by'];
    $new_value[20] = $value['staff_name'];
    $new_value[21] = $value['branch'];
    $new_value[22] = $value['region'];

    $output .= getCSV($new_value);
}
echo $output;exit();
?>

1 个答案:

答案 0 :(得分:2)

fputcsv希望将一维值数组写入为CSV数据的一个“行”。

但是通过使用

,您的$heading并不是这样的一维数组
$heading[] = array('Customer ID', ...);

您将其制成了二维二维。

删除方括号:

$heading = array('Customer ID', ...);