0

我正在尝试加快此 PHP 代码的性能。我在 XAMPP 上使用 Apache 和 MYSQL 通过浏览器运行它。

我的问题是我正在读取一个非常大的 2GB JSON 文件。我无法一口气读完,因为我没有足够的内存,因此我必须逐行阅读

代码逐行读取 JSON。对于每一行(JSON 数据块),调用一个函数 (Function parse_item),该函数解码 JSON 行,然后打开 mysql 数据库并从解码的 JSON 行中插入选定的数据,然后关闭 MySQL 数据库。我知道它插入数据库导致我的性能问题,但不知道该怎么做。(即当我删除数据库并只回显解码的 JSON 时,速度要快得多)

代码(一个缩写的切片)可以工作,但速度很慢......................

有人可以帮忙吗?我是 PHP 新手,所以任何简单的解释都将不胜感激。

另外.......如果我从命令行运行它(即将PHP加载到我的PC)它会运行得更快吗?

谢谢约翰

//Parse Function
function parse_item($string) {

$data = json_decode($string);


$uid=($data->JsonScheduleV1->CIF_train_uid);
$stp=($data->JsonScheduleV1->CIF_stp_indicator);                                                      
$head=($data->JsonScheduleV1->schedule_segment->signalling_id);       
$startlocation=($data->JsonScheduleV1->schedule_segment->schedule_location[0]->tiploc_code);

require('connect_db.php');
mysqli_select_db($mysql_link,"timetable");
mysqli_query($mysql_link,"INSERT INTO railstp (uid,stp,head,startlocation)
  VALUES ('$uid','$stp','$head','$startlocation')");
mysqli_close($mysql_link);

if (is_null($data)) {
   die("Json decoding failed with error: ". json_last_error());
}

}


$file = 'CIF_PA_TOC_FULL_DAILY_toc-full';

// Slices up the JSON into lines and then
parse_item($string);



//

编辑

我有一个 InnoDB 数据库 有 20 个键 - 2 个是整数,2 个是日期,其余文本 不确定有多少行,但猜测超过 1,000 行 - 无法运行足够长的时间

4

1 回答 1

1

创建 MySQL 连接并在每个parse_item()函数调用时关闭它会浪费你的脚本时间,而且你的if语句没有足够的函数!所以我会重写你的代码:

require('connect_db.php');
mysqli_select_db($mysql_link,"timetable");
function parse_item($string,&$mysql_link) {
  $data = json_decode($string);
  if (is_null($data)) {
     mysqli_close($mysql_link);die("Json decoding failed with error: ". json_last_error());
  }
  $uid=($data->JsonScheduleV1->CIF_train_uid);
  $stp=($data->JsonScheduleV1->CIF_stp_indicator);                                                      
  $head=($data->JsonScheduleV1->schedule_segment->signalling_id);       
  $startlocation=($data->JsonScheduleV1->schedule_segment->schedule_location[0]->tiploc_code);
  mysqli_query($mysql_link,"INSERT INTO railstp (uid,stp,head,startlocation)
                            VALUES ('$uid','$stp','$head','$startlocation')");
}


$file = 'CIF_PA_TOC_FULL_DAILY_toc-full';
$handle = fopen("c:\\folder\$file" , "r");
while(!feof($handle)){
   $string=fgets($handle); 
   parse_item($string,$mysql_link);       //REMEMBER: to pass your $mysql_link variable!
}
fclose($handle);
mysqli_close($mysql_link);

我希望这对你有帮助。

于 2013-09-08T17:44:12.453 回答