我正在尝试将生成的Excel工作表保存到服务器。它可以保存,但Excel工作表为空。我正在使用以下代码。
$sql = "select name, email from agencies";
$result = mysqli_query($conn, $sql);
$resultRows = mysqli_fetch_assoc($result);
if($resultRows>0){
$sep = "\t"; //tabbed character
//while($rowheading = mysqli_fetch_field($result)) { echo $rowheading->name . $sep; }
while($finfo = $result->fetch_field())
{
printf($finfo->name . $sep);
}
print("\n");
while($row = mysqli_fetch_row($result)){
$schema_insert = "";
for($j=0; $j<mysqli_num_fields($result);$j++){
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim(str_replace(',', " ", $schema_insert)));
print "\n";
}
file_put_contents('/var/www/html/myfiles/public/core/enquiry_mail_sms/file/Report.xls', $schema_insert);
}
mysqli_close($conn);
我不了解出了什么问题。有人可以指导我吗?
答案 0 :(得分:0)
来自docs(重点是我):
如果
filename
不存在,则创建文件。否则,除非设置了FILE_APPEND
标志,否则现有文件将被覆盖。
(假设您实际上是说您仅获得 last 记录,而不是 first 。)
答案 1 :(得分:0)
问题是您在循环的每次迭代中都覆盖了文件,因此现在在文件中您只会看到最后一条记录。
为避免将file_put_contents()
移出循环
$sql = "select name, email from agencies";
$result = mysqli_query($conn, $sql);
$resultRows = mysqli_fetch_assoc($result);
if($resultRows>0){
$sep = "\t"; //tabbed character
//while($rowheading = mysqli_fetch_field($result)) { echo $rowheading->name . $sep; }
while($finfo = $result->fetch_field())
{
printf($finfo->name . $sep);
}
print("\n");
$excelContent = '';
while($row = mysqli_fetch_row($result)){
$schema_insert = "";
for($j=0; $j<mysqli_num_fields($result);$j++){
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
$excelContent .= $schema_insert
print(trim(str_replace(',', " ", $schema_insert)));
print "\n";
}
file_put_contents('/var/www/html/myfiles/public/core/enquiry_mail_sms/file/Report.xls', $excelContent);
}
mysqli_close($conn);