首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PHP将大型xml文件导入/更新到MySQL

问使用PHP将大型xml文件导入/更新到MySQL
EN

Stack Overflow用户
提问于 2011-04-06 05:19:51
回答 6查看 5K关注 0票数 0

我在一个XML文件中有大约30K条记录,并且这个文件一直在更新。

我正在尝试插入并更新一个MySQL数据库。

这是我想使用的代码,但它运行非常慢,有谁有任何想法来提高它的性能吗?

代码语言:javascript
复制
// getting xml file
$dom = new DOMDocument();
$dom->load('products.xml');

// getting xml nodes using xpath
$xpath = new DOMXPath($dom);
$productid = $xpath->query('//NewDataSet/Product/ProductId');
$price = $xpath->query('//NewDataSet/Product/Price');

// Reading all nodes and if mach found in db update price, else insert as new record**
for($i=0;$i<$allNodes->length;$i++){
    $testproductid = $productid->item($i)->nodeValue;
    $testprice = $price->item($i)->nodeValue;
    if(mysql_num_rows(mysql_query("Select productid from test where productid ='$testproductid'"))){
        mysql_query("UPDATE test SET price = '$testprice' WHERE productid = '$testproductid'");
    }else{
        mysql_query("INSERT INTO test (price, productid) VALUES ('$testprice','$testproductid')");
    }
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-04-06 05:30:05

首先,这一行可能会导致不良行为:

代码语言:javascript
复制
if(mysql_num_rows(mysql_query("Select productid from test where productid ='$testproductid'")))

如果mysql_query()失败了会发生什么?做一些像这样的事情:

代码语言:javascript
复制
$res = mysql_query("Select productid from test where productid ='$testproductid'");
if ($res) {
... CODE HERE ...
}

productid是索引吗?此外,您还可以将查询格式化为:

代码语言:javascript
复制
Select productid from test where productid ='$testproductid' LIMIT 1

在这种情况下,MySQL不会查找更多的记录。另外,尝试在on single insert语句中插入多条记录。请看以下内容:

http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html

看一下REPLACE命令。这将替换SELECT/UPDATE/INSERT条件,但这可能不会大大提高性能。

http://dev.mysql.com/doc/refman/5.0/en/replace.html

票数 0
EN

Stack Overflow用户

发布于 2011-04-06 05:23:12

首先,我建议复习一些MySQL。其次,通过在SQL域上使用主键,您可以使用一个更高级的productid语句:insert ... on duplicate key update ...

It's gonna halve your database lookups for the first part,因为您在插入/更新之前要做一个额外的测试。

其次,XML可能不是跨平台文件的最佳解决方案。你使用这个有什么特别的原因吗?

票数 0
EN

Stack Overflow用户

发布于 2011-04-06 05:27:14

为什么要有两个查询,而一个查询就足够了?

代码语言:javascript
复制
$sql = "INSERT INTO test (price, productid) " .
       "VALUES ('$testprice','$testproductid') " .
       "ON DUPLICATE KEY UPDATE";

if(!$query = mysql_query($sql))
   trigger_error(mysql_error());

你也可以尝试用SimpleXML来代替DOMDocument,但从我用谷歌搜索得到的信息来看,似乎没有任何有记录的速度差异。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5558675

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档