PHP中最快的XML解析器是什么?

2022-08-30 19:16:34

对于某个项目,我需要一些方法来解析XML并从中获取数据。所以我想知道,哪一个内置的解析器是最快的?

另外,解析器可以接受XML字符串作为输入会很好 - 我有自己的线程安全处理文件的实现,我不希望一些讨厌的非线程安全库使我的努力无用。


答案 1

最快的解析器将是SAX - 它不必创建dom,可以使用部分xml或渐进式完成。有关 PHP SAX 解析器(Expat)的信息可以在这里找到。或者,有一个名为 SimpleXML 的基于 libxml 的 DOM 解析器。基于DOM的解析器将更容易使用,但它通常慢几个数量级。


答案 2

**这主要针对那些从XML解析开始并且不确定要使用哪个解析器的人。

解析有两种“大”方法 - 您可以将XML加载到内存中并找到所需的内容(DOM,SimpleXML),也可以对其进行流式传输 - 读取它并根据您读取的内容执行代码(XMLReader,SAX)。

根据微软的说法,SAX是一个“推送”解析器,它将每条信息发送到您的应用程序,您的应用程序对其进行处理。SimpleXML是一个“拉”解析器,它允许您跳过数据块并仅获取所需的数据块。根据微软的说法,这可以简化和加速你的应用程序,我假设.NET和PHP的实现是相似的。我想你的选择将取决于你的需求 - 如果你从一个更大的块中提取几个标签,并且可以使用跳过重要的块,你可能会发现XMLReader比SAX更快。$xml->next('Element')

重复解析“小”(<30kb,700 行)XML 文件,您可能不希望解析方法之间存在巨大的时间差。我很惊讶地发现有。我对在 SimpleXML 和 XMLReader 中处理的小源进行了比较。希望这将有助于其他人可视化此数据的差异有多大。对于实际情况的比较,这是对两个亚马逊 MWS 商品信息请求源的响应。

每个解析时间是获取 2 个 XML 字符串并返回大约 120 个包含每个字符串值的变量所需的时间。每个循环采用不同的数据,但每个测试都以相同的顺序对相同的数据进行。

SimpleXML 将文档加载到内存中。我使用微时间来检查完成解析的时间(提取相关值)以及创建元素所花费的时间(调用时间)。我已将这些四舍五入到小数点后4位。new SimpleXMLElement($xml)

Parse Time: 0.5866 seconds
Parse Time: 0.3045 seconds 
Parse Time: 0.1037 seconds
Parse Time: 0.0151 seconds 
Parse Time: 0.0282 seconds 
Parse Time: 0.0622 seconds 
Parse Time: 0.7756 seconds
Parse Time: 0.2439 seconds  
Parse Time: 0.0806 seconds 
Parse Time: 0.0696 seconds
Parse Time: 0.0218 seconds
Parse Time: 0.0542 seconds
__________________________
            2.3500 seconds
            0.1958 seconds average

Time Spent Making the Elements: 0.5232 seconds 
Time Spent Making the Elements: 0.2974 seconds 
Time Spent Making the Elements: 0.0980 seconds 
Time Spent Making the Elements: 0.0097 seconds 
Time Spent Making the Elements: 0.0231 seconds 
Time Spent Making the Elements: 0.0091 seconds 
Time Spent Making the Elements: 0.7190 seconds 
Time Spent Making the Elements: 0.2410 seconds 
Time Spent Making the Elements: 0.0765 seconds 
Time Spent Making the Elements: 0.0637 seconds 
Time Spent Making the Elements: 0.0081 seconds 
Time Spent Making the Elements: 0.0507 seconds 
______________________________________________
                                2.1195 seconds
                                0.1766 seconds average
over 90% of the total time is spent loading elements into the DOM.

Only 0.2305 seconds is spent locating the elements and returning them.

虽然XMLReader是基于流的,但我能够跳过其中一个XML源的重要部分,因为我想要的数据靠近每个元素的顶部。“您的里程可能会有所不同。

Parse Time: 0.1059 seconds  
Parse Time: 0.0169 seconds 
Parse Time: 0.0214 seconds 
Parse Time: 0.0665 seconds 
Parse Time: 0.0255 seconds 
Parse Time: 0.0241 seconds 
Parse Time: 0.0234 seconds 
Parse Time: 0.0225 seconds 
Parse Time: 0.0183 seconds 
Parse Time: 0.0202 seconds 
Parse Time: 0.0245 seconds 
Parse Time: 0.0205 seconds 
__________________________
            0.3897 seconds
            0.0325 seconds average

引人注目的是,尽管一旦加载完所有内容,在 SimpleXML 中查找元素的速度会稍快一些,但实际上使用 XMLReader 的速度要快 6 倍以上。

您可以在如何在PHP中使用XMLReader中找到有关使用XMLReader的一些信息。


推荐