**这主要面向那些从 XML 解析开始但不确定使用哪个解析器的人。
有两种“大”方法可以进行解析 - 您可以将 XML 加载到内存中并找到您需要的内容(DOM、SimpleXML),或者您可以流式传输它 - 读取它并根据您读取的内容执行代码( XMLReader, SAX)。
According to Microsoft,SAX 是一个“推送”解析器,它将每条信息发送到您的应用程序并由您的应用程序处理。 SimpleXML 是一个“拉式”解析器,它允许您跳过数据块并只获取您需要的数据。根据 Microsoft 的说法,这可以简化和加速您的应用程序,我认为 .NET 和 PHP 实现是相似的。我想你的选择取决于你的需要——如果你只是从一个较大的块中提取几个标签并且可以使用$xml->next('Element') 来跳过重要的块,你可能会发现 XMLReader 比 SAX 更快。
重复解析“小”(
每个 Parse Time 是获取 2 个 XML 字符串并返回大约 120 个包含每个字符串值的变量所需的时间。每个循环采用不同的数据,但每个测试都以相同的顺序对相同的数据进行。
SimpleXML 将文档加载到内存中。我使用 microtime 检查完成解析的时间(提取相关值)以及创建元素所花费的时间(调用 new SimpleXMLElement($xml) 时)。我已将这些四舍五入到小数点后 4 位。
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 倍以上。
您可以在How to use XMLReader in PHP?找到有关使用 XMLReader 的一些信息