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

查看:30
本文介绍了在 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天全站免登陆