标题行未显示在csv文件中

时间:2016-03-21 17:47:26

标签: php csv mysqli

HY! 我已将数据库表中的所有信息提取到csv文件中。 现在我试图给每行标题,并希望它显示为键,值对。 为此,我制作逻辑,但这不起作用。 请建议最好的解决方案。

$sql = "select * from log";
$result = mysqli_query($link, $sql) or die("Selection Error " . mysqli_error($connection));

$fp = fopen('logInfo.csv', 'w');

while($row = mysqli_fetch_assoc($result) && $row = fgetcsv($fp))
{
    $all_rows = array();
    $header = null;

    if ($header === null) {
        $header = $row;
        continue;
    }
    $all_rows[] = array_combine($header, $row);

    fputcsv($fp, $row);       
}

2 个答案:

答案 0 :(得分:2)

您每次都要重置$header 试试这个:

$header   = null;
while($row = mysqli_fetch_assoc($result))
{
    if ($header === null) {
        $header = $row;
        continue;
    }
    fputcsv($fp, $header);
    fputcsv($fp, $row); 

}

答案 1 :(得分:1)

如果您想将标题行作为csv文件的第一行

$header = null;
while($row = mysqli_fetch_assoc($result))
{
    if ($header === null) {
        $header = array_keys($row);
        fputcsv($fp, $header);       
    }

    fputcsv($fp, $row);       
}