PHP数组CSV下载集成到我当前的脚本不能正常工作


php array to csv download integrated into my current script not working properly

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

我试图将我完成的查询结果数组转换为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);
}

我这样解决了这个问题:

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);
}

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

我们知道CSV代表逗号分隔的值,所以它基于逗号值进行分割,所以像"JOJO Associates, Inc."这样的字符串中的逗号将被视为两个单独的值。在其周围添加双引号("),因此它将

视为单个值