在PHP中处理大型XML的最佳方法 [英] Best way to process large XML in PHP

查看:61
本文介绍了在PHP中处理大型XML的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在php中解析大型XML文件,其中之一是6.5 MB,甚至可能更大. 如我所读,SimpleXML扩展将整个文件加载到一个对象中,这可能不是很有效. 以您的经验,最好的方法是什么?

I have to parse large XML files in php, one of them is 6.5 MB and they could be even bigger. The SimpleXML extension as I've read, loads the entire file into an object, which may not be very efficient. In your experience, what would be the best way?

推荐答案

对于大文件,您需要使用 SAX解析器,而不是DOM解析器.

For a large file, you'll want to use a SAX parser rather than a DOM parser.

使用DOM解析器,它将读取整个文件并将其加载到内存中的对象树中.使用SAX解析器,它将依次读取文件并调用用户定义的回调函数来处理数据(开始标签,结束标签,CDATA等)

With a DOM parser it will read in the whole file and load it into an object tree in memory. With a SAX parser, it will read the file sequentially and call your user-defined callback functions to handle the data (start tags, end tags, CDATA, etc.)

使用SAX解析器时,您需要自己维护状态(例如,您当前所处的标记),这会使它变得更加复杂,但是对于大文件,这将是更有效的内存使用方式.

With a SAX parser you'll need to maintain state yourself (e.g. what tag you are currently in) which makes it a bit more complicated, but for a large file it will be much more efficient memory wise.

这篇关于在PHP中处理大型XML的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆