php阵列到csv下载集成到我当前的脚本不能正常工作

时间:2012-01-03 05:01:58

标签: php arrays loops download

我在这个主题上找到了一些有用且有用的教程和论坛帖子。但我找不到任何显示我当前场景的确切示例和实现。

我正在尝试将完成的查询结果数组转换为csv格式,因此我可以以.csv格式下载格式正确的结果。

以下是我的代码:

这是我的下载操作:

<script>
    function getcsv(){
    window.location="script_4.php";
}
</script>
<input type="button" onclick="getcsv()" value="Download CSV">

这是我的while()循环将我的查询数据合并到一个连续的数字数组中:

while ($row = mysql_fetch_row($result)) {
$industries = explode(",", $row[3]);
unset($row[3]);
$merge = array_merge($row, $industries);
echo "<pre>";
print_r($merge);
echo "</pre>";
}

我上面的print_r()回应如下:

Array
(
    [0] => 3561
    [1] => The Ace Company
    [2] => ace@not-a-real-site.com
    [3] => Waterproofing
)
Array
(
    [0] => 3562
    [1] => JOJO Associates, Inc.
    [2] => joj@not-a-real-site.com
    [3] => Lab Equipment & Casework
)
Array
(
    [0] => 3564
    [1] => Southern Style Pipe
    [2] => southern@no-a-real-site.com
    [3] => Plumbing
    [4] => Piping
    [5] => Pipe Inspection
)

这是我使用下载脚本的地方,当我尝试它时,它将我的html和整个数组加载到csv中,没有csv格式的数组数据。

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

outputCSV($merge);

function outputCSV($data) {
    $outstream = fopen("php://output", "w");
    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals);
    }
    array_walk($data, "__outputCSV", $outstream);
    fclose($outstream);
}

2 个答案:

答案 0 :(得分:1)

我解决了这个问题:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=exhibitors-$date.csv");
header("Pragma: no-cache");
header("Expires: 0");
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('ID', 'Company', 'Email', 'Address1', 'Address2', 'City',     'State', 'Province', 'Zip', 'Phone', 'Fax', 'Toll Free', 'Site'));
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////////////////////////////////////////////////////
while ($row = mysql_fetch_row($result)) {
        $industries = explode(",", $row[13]);
        unset($row[13]);
    $merge = array_merge($row, $industries);
    fputcsv($output, $merge);
}

答案 1 :(得分:0)

我认为地址字段中的逗号(,)导致问题,在字符串周围加上双引号以便它可以工作

我们知道CSV代表逗号分隔值,因此它会根据逗号值进行拆分,因此字符串中的逗号(如“ JOJO Associates,Inc。”)将被视为两个单独的值。在它周围添加双引号(“),因此它将其视为单个值