我正在尝试解析 xml 文件以将数据存储到数据库中。我用 PHP 编写了一段代码(如下所示),我可以成功运行该代码。
但问题是,读取一个完整的文件(大约 30 MB)需要大约 8 分钟,而且我每小时必须解析大约 100 个文件。
所以,显然我当前的代码对我没有用。有人可以建议更好的解决方案吗?或者我应该切换到其他编码语言?
我从网上得到的是,我可以使用 Perl/Python 或称为 XSLT 的东西(坦率地说,我不太确定)。
$xml = new XMLReader();
$xml->open($file);
while ($xml->name === 'node1'){
$node = new SimpleXMLElement($xml->readOuterXML());
foreach($node->node2 as $node2){
//READ
}
$xml->next('node1');
}
$xml->close();
请您参考如下方法:
这是我用来解析 WURFL XML 数据库的脚本示例 found here .
我使用了 Python 的 ElementTree 模块并编写了一个 JavaScript 数组 - 尽管您可以轻松修改我的脚本以编写相同的 CSV(只需更改最后 3 行)。
import xml.etree.ElementTree as ET
tree = ET.parse('C:/Users/Me/Documents/wurfl.xml')
root = tree.getroot()
dicto = {} #to store the data
for device in root.iter("device"): #parse out the device objects
dicto[device.get("id")] = [0, 0, 0, 0] #set up a list to store the needed variables
for child in device: #iterate through each device
if child.get("id") == "product_info": #find the product_info id
for grand in child:
if grand.get("name") == "model_name": #and the model_name id
dicto[device.get("id")][0] = grand.get("value")
dicto[device.get("id")][3] +=1
elif child.get("id") == "display": #and the display id
for grand in child:
if grand.get("name") == "physical_screen_height":
dicto[device.get("id")][1] = grand.get("value")
dicto[device.get("id")][3] +=1
elif grand.get("name") == "physical_screen_width":
dicto[device.get("id")][2] = grand.get("value")
dicto[device.get("id")][3] +=1
if not dicto[device.get("id")][3] == 3: #make sure I had enough
#otherwise it's an incomplete dataset
del dicto[device.get("id")]
arrays = []
for key in dicto.keys(): #sort this all into another list
arrays.append(key)
arrays.sort() #and sort it alphabetically
with open('C:/Users/Me/Documents/wurfl1.js', 'w') as new: #now to write it out
for item in arrays:
new.write('{\n id:"'+item+'",\n Product_Info:"'+dicto[item][0]+'",\n Height:"'+dicto[item][1]+'",\n Width:"'+dicto[item][2]+'"\n},\n')
我在再次运行时计算了一下 - 大约用了 3 秒。
