PHP从数据库写入800条记录到文件(.txt)

时间:2013-11-11 08:54:17

标签: php mysql

我正在尝试从数据库中访问超过8000个包含30列的记录,并写入由制表符分隔的文本文件。 我的PHP代码是:

 $fp1 = fopen( 'obspg.txt', 'w' );
  fwrite( $fp1,"RETSKU\tProduct Title\tDetailed Description\tProduct Condition\tSelling Price\tAvailability\tProduct URL\tImage URL\tManufacturer Part Number\tManufacturer Name\tCategorization\tGender\tsize\tColor\n");
  //retrive records from database and write to file
  $result = mysqli_query($con,"SELECT * FROM `TABLE 1` ");
  while($row = mysqli_fetch_array($result))
  {
     fwrite($fp1,$row[`id`]."\t".$row[`title`]."\t".  $row[`description`]."\t".$row[`condition`]."\t". $row[`price`]."\t".$row[`availability`]."\t".$row[`link`]."\t". $row[`image_link`]."\t".$row[`mpn`]."\t".$row[`brand`]."\t".$row[`google_product_category`]."\t".$row[`Gender`]."\t".$row[`size`]."\t".$row[`Color`]."\n");
  } 
  fclose( $fp1 );

但执行时间太长。如何提高代码性能?我的服务器使用率不能超过25%。

1 个答案:

答案 0 :(得分:2)

构造你想要在变量中写入的数据,然后只写一个文件。它更有效率。

$fp1 = fopen( 'obspg.txt', 'w' );

$outPut = "RETSKU\tProduct Title\tDetailed Description\tProduct Condition\tSelling Price\tAvailability\tProduct URL\tImage URL\tManufacturer Part Number\tManufacturer Name\tCategorization\tGender\tsize\tColor\n";

//retrive records from database and write to file
$result = mysqli_query($con,"SELECT * FROM `TABLE 1` ");
while($row = mysqli_fetch_array($result))
{
 $outPut .= $row[`id`]."\t".$row[`title`]."\t".  $row[`description`]."\t".$row[`condition`]."\t". $row[`price`]."\t".$row[`availability`]."\t".$row[`link`]."\t". $row[`image_link`]."\t".$row[`mpn`]."\t".$row[`brand`]."\t".$row[`google_product_category`]."\t".$row[`Gender`]."\t".$row[`size`]."\t".$row[`Color`]."\n";
} 

fwrite( $fp1,$outPut);
fclose( $fp1 );