Selecting parent nodes with XMLReader

前端 未结 3 1121
旧巷少年郎
旧巷少年郎 2020-12-20 00:16

I had to rewrite part of a programme to use XMLReader to select parts of an XML file for processing.

Take this simplified XML as an example:



        
3条回答
  •  执笔经年
    2020-12-20 00:45

    DOMXPath is said to be more robust than SimpleXML with respect to performance (it has other advantages, e.g. it can properly deal with namespaces). See for example this IBM article for a discussion of several XPath libraries in PHP.

    I'm just curious if your performance issue would persist (or still be as severe) when using DOMXPath:

    load('sample.xml');
    $xpath = new DOMXPath($doc);
    
    $nodes = $xpath->query("/odds/sport/region/group/event/bet[selection/@selectionid = '52411062.1']");
    
    foreach ($nodes as $node)
    {
       print $xml = $node->ownerDocument->saveXML($node);
    }
    ?>
    

    The result, taking as input the small snippet you have shown, is

    
        
    
    

    If that does not help, you really have to resort to an event-based (pull-style) XML parser, that does not read the whole document into memory - as Yasen suggests.

提交回复
热议问题