【发布时间】:2014-04-12 14:22:28
【问题描述】:
$files = glob('dataset/*.xml');
foreach ($files as $key => $txc) {
$txcDoc = new DOMDocument();
$txcDoc->load($txc);
$operators = $txcDoc->getElementsByTagName("Operators");
foreach ($operators as $operatorTag) {
foreach ($operatorTag->getElementsByTagName("Operator") as $operator) {
$reference = $operator->getAttribute("id");
@$nationalOperatorCode = $operator->getElementsByTagName("NationalOperatorCode")->item(0)->nodeValue;
$operatorCode = $operator->getElementsByTagName("OperatorCode")->item(0)->nodeValue;
$operatorShortName = $operator->getElementsByTagName("OperatorShortName")->item(0)->nodeValue;
@$operatorNameOnLicense = $operator->getElementsByTagName("OperatorNameOnLicense")->item(0)->nodeValue;
@$tradingName = $operator->getElementsByTagName("TradingName")->item(0)->nodeValue;
$operatorSQL = "INSERT IGNORE INTO `operator` (`reference`, `national_operator_code`, `operator_code`, `operator_short_name`, `operator_name_on_license`, `trading_name`) VALUES (:reference, :nationalOperatorCode, :operatorCode, :operatorShortName, :operatorNameOnLicense, :tradingName);";
$operatorStmt = $conn->prepare($operatorSQL);
$operatorStmt->execute(array(':reference' => $reference, ':nationalOperatorCode' => $nationalOperatorCode, ':operatorCode' => $operatorCode, ':operatorShortName' => $operatorShortName, ':operatorNameOnLicense' => $operatorNameOnLicense, ':tradingName' => $tradingName));
}
}
}
上面的 PHP 循环遍历 78,654 个 XML 文件 (1.2gb),解析它们的数据,然后将数据插入 MySQL 数据库。上面的 sn-p 只占文件的十分之一,但是还有另外 10-15 个 foreach 构造,就像 foreach ($operators 一样。 (查看整个文件请点击here)
我的问题是插入 250 个文件的数据需要 10-20 分钟。我需要大幅提高速度,以便在
数据库引擎是 MySQL,表都是 InnoDB。我怎样才能加快这些插入速度?
【问题讨论】: