[英]writing large xml file to mysql table is too slow possibly due to foreach loop?
希望在這里得到一些幫助。 我有一個大的xml文件(在上面的代碼中稱為xml-file.xml)。 我在上面的代碼中遇到的問題是將所有內容寫入數據庫非常慢。 我認為它很慢的原因是因為部分循環播放電影並且只用逗號分隔的字符串將電影名稱寫入表格。 我的問題 - 是否有更有效的方法將電影名稱轉換為逗號分隔的字符串,然后寫入表格? 在此先感謝您的幫助!
XML標記:
<users>
<user>
<id>7280462</id>
<name>John</name>
<movies>
<name>
<![CDATA[Jack]]>
</name>
<description>
<![CDATA[comedy]]>
</description>
<name>
<![CDATA[Superman]]>
</name>
<description>
<![CDATA[action]]>
</description>
<name>
<![CDATA[Ace Venture]]>
</name>
<description>
<![CDATA[comedy]]>
</description>
<name>
<![CDATA[Major League]]>
</name>
<description>
<![CDATA[sports]]>
</description>
</movies>
</user>
</users>
我的PHP代碼:
$file = 'xml-file.xml';
$users = simplexml_load_file($file);
$num_rows = count($users);
for ($j=0; $j < $num_rows; $j++) {
$userid = $users->user[$j]->id;
$name = $users->user[$j]->name;
//update table with userid and name
$db->exec("INSERT INTO table (userid, name) VALUES ('$userid', '$name')");
//loop through movies and write only movie name to table as comma separated string
foreach ($users->user$j]->movies as $element) {
foreach($element as $key => $val) {
if ($key != 'description') {
//echo "{$key}: {$val}";
$title = trim($val).',';
$db->exec("UPDATE table set movies = concat(movies,'','$title') where userid = '$userid'");
}
}
}
}
這個怎么樣:
for ($j=0; $j < $num_rows; $j++) {
$userid = $users->user[$j]->id;
$name = $users->user[$j]->name;
$titles = "";
foreach ($users->user$j]->movies as $element) {
foreach($element as $key => $val) {
if ($key != 'description') {
$titles .= trim($val).',';
}
}
}
$titles = trim($titles, ",");
$db->exec("INSERT INTO table (userid, name, movies) VALUES ('$userid', '$name','$titles')");
}
它一次性生成所有SQL,因此您只需要一個語句。
首先對您的數據庫進行零售。 這將避免使用concat等。請查看Google。
您需要確保您的查詢知道任何索引,或者如果沒有索引創建索引。
MySql中的EXPLAIN
關鍵字是你的朋友。 它會告訴你發生了什么或沒發生什么。
另外,更改XML的格式並使用DOM。
有一個標簽“電影”,其中只包含有關電影的詳細信息。
即
<movies>
<movie>
<name>Jack</name>
<description>Comedy</descript>
</movie>
<movie>
<name>Superman</name>
<description>Action</description>
</movie>
....
</movies>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.