我正在用PHP编写一个应用程序,该应用程序将使用来自API的数据进行大量计算。我让它都工作,除了它是超级慢,因为每个请求最终通过5个独立的JSON文件(通常有许多字段,我从来没有需要。
我想到的一个可能的解决方案是简单地创建一个文件来处理所有内容,并将其插入到数据库中,这样我就可以创建更有效的查询,只获取我需要的值。
我把这些都设置好了,但是因为它试图处理一个巨大的JSON文件(http://api.vex.us.nallen.me/get_teams),它最终在插入任何东西之前超时了。
这是我创建的处理团队的文件。
<?php
$url = "http://api.vex.us.nallen.me/get_teams?nodata=true";
$json = file_get_contents($url);
$json_decoded = json_decode($json);
$number_of_teams = $json_decoded->{'size'};
$teams_updated = 0;
echo $number_of_teams;
$hostname = "host";
$username = "user";
$password = "pw";
$database = "db";
$dbConnection = new mysqli($hostname,$username,$password,$database);
if($dbConnection->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
while($teams_updated < $number_of_teams) {
$url = "http://api.vex.us.nallen.me/get_teams?limit_start=".$teams_updated."&limit_number=1000";
$json = file_get_contents($url);
$json_decoded = json_decode($json);
for( $i = 0; $i < count($json_decoded->{'result'}); $i++) {
$team = $json_decoded->{'result'}[$i];
$number = $team->{'number'};
$program = $team->{'program'};
$team_name = $team->{'team_name'};
$robot_name = $team->{'robot_name'};
$organisation = $team->{'organisation'};
$city = $team->{'city'};
$country = $team->{'country'};
$grade = $team->{'grade'};
if ($stmt = $dbConnection->prepare("INSERT INTO teams (number, program, team_name, robot_name, organisation, city, country, grade) VALUES(?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE number=?, program=? team_name=?, robot_name=?, organisation=?, city=?, country=?, grade=?")) {
$stmt->bind_param('ssssssss', $number, $program, $team_name, $robot_name, $organisation, $city, $country, $grade);
$stmt->execute();
$teams_updated++;
}
}
}
?>
是否有更有效的JSON解析器或不同的方法,我应该使用来处理所有这些数据?
你可以简单地用两步来完成:
- 做一个脚本(PHP或其他,没关系),将处理你的JSON文件,并转换为SQL指令
LOAD DATA INFILE
(即csv-ish)使用的格式。 - 从命令行使用原始SQL查询执行实际的插入,您不需要脚本(奖励:没有超时)。