【问题标题】:Export MySQL Data to a CSV file using PHP is displaying 1 row and blank CSV使用 PHP 将 MySQL 数据导出到 CSV 文件显示 1 行和空白 CSV
【发布时间】:2013-04-16 10:36:05
【问题描述】:

我有这段代码可以将 MySQL 数据导出到 CSV 文件,但是当我回显结果时它只显示数据库中的 1 行,即使我在 PHP My Admin 中运行 SQL,它也会显示大约 29 行。

它只是生成一个空白的 CSV 文件

$sql="select description, jobreceived, timebookedfor, bookedfor,
      site_contact, site_address, invoice_contact, invoice_address,
      quotedprice, cleardowndetails, notes, mo_number from jobs ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$filename="jobs.csv";
$file=fopen($filename,"w");
//$output="sequence,firstname,surname,email,membertype\n";
fwrite($file,$output);
while($result=mysql_fetch_array($rs))
{
    echo $result["description"].','.$result["jobreceived"].'<br>';
    //$output=$result["sequence"].",".$result["name"].","
              .$result["email"].",".$result["country"]."\n";
    $output=proper($result["description"]).",".$result["jobreceived"]
           ."\r\n";
    fwrite($file,$output);
}
fclose($file);
function proper($string)
{
    $first=strtoupper(substr($string,0,1));
    $rest=strtolower(substr($string,1));
    $result=$first.$rest;
    return $result;
}

【问题讨论】:

  • 开始使用 PHP 内置的 fputcsv() 函数 (php.net/manual/en/function.fputcsv.php)
  • 错误日志是怎么说的?
  • 什么错误日志?我尝试使用 fputcsv 而不是 fopen 但仍然没有
  • 您对目录和jobs.csv 文件有写权限吗? (你说它是空白的,所以我假设它已经存在)你应该通过if(!$file) echo 'cannot open jobs.csv for writing'; 进行检查

标签: php mysql csv export


【解决方案1】:

这两个功能就可以搞定

function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"')
{
    if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
    {
        show_error('You must submit a valid result object');
    }

    $out = '';

    // First generate the headings from the table column names
    foreach ($query->list_fields() as $name)
    {
        $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
    }

    $out = rtrim($out);
    $out .= $newline;

    // Next blast through the result array and build out the rows
    foreach ($query->result_array() as $row)
    {
        foreach ($row as $item)
        {
            $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
        }
        $out = rtrim($out);
        $out .= $newline;
    }

    return $out;
}

function write_file($path, $data, $mode = 'wb')
{
    if ( ! $fp = @fopen($path, $mode))
    {
        return FALSE;
    }

    flock($fp, LOCK_EX);
    fwrite($fp, $data);
    flock($fp, LOCK_UN);
    fclose($fp);

    return TRUE;
}

将您的查询对象传递给函数。

$sql="select
          description,
          jobreceived,
          timebookedfor,
          bookedfor,
          site_contact,
          site_address,
          invoice_contact,
          invoice_address,
          quotedprice,
          cleardowndetails,
          notes,
          mo_number
        from jobs";
$rs =   mysql_query($sql,$conn) or die(mysql_error());

现在将资源传递给csv_from_result 函数

$file_data  =   csv_from_result($rs);

现在你可以写文件了

$filename   =   "jobs.csv"; 
write_file($filename , $file_data); // $filename can be a complete path

或回显查看 csv 结果

echo $file_data;

【讨论】:

  • 您好,您可以在使用其他作者编写的代码时引用您的来源吗?
  • 既然 PHP 有非常出色的内置函数可以为您完成这项工作,为什么还要编写自己的函数来创建 CSV 格式的输出?
  • 是的,这两个函数在名为Codeigniter的伟大PHP框架中是可用的
  • excel 会将 0001 解释为 1,因此 fputcsv 并没有你想象的那么优越。 '0001' 是一个字符串
  • 这个函数有一些检查,它可以正确处理错误。人们不希望在他的屏幕上出现任何不希望出现的错误。这只是一次工作。下次您将简单地将其用作函数用于此目的。
【解决方案2】:

也许你应该尝试删除 fwrite($file,$output);循环中的语句。如果查询结果按预期回显,那么问题显然是 fwrite 语句(可能是文件权限)。 如果结果未按预期回显,则您的查询结果可能存在问题。 此外,作为建议,请确保按照 fopen 手册的规定,为操作系统使用正确的行尾字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    相关资源
    最近更新 更多