Replacing Parsing function with XMLReader in Specific PHP Code

前端 未结 1 471
执念已碎
执念已碎 2021-01-28 02:58

I\'m trying to utilize a PHP script to parse a large XML file (around 450 MB) to MYSQL database into certain structure and definitions to included XML elements. The problem is t

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-28 03:47

    It is possible to expand a XML reader position to a DOMElement. This element is not associated with an DOMDocument, so it can not be converted into a SimpleXMLElement directly, but it can be imported into a DOMDocument.

    $xml = <<<'XML'
    
      
    
    XML;
    
    $reader = new XMLReader;
    $reader->open('data://text/xml;base64,'.base64_encode($xml));
    
    $dom = new DOMDocument;
    
    // look for the first template element
    while ($reader->read() && $reader->localName !== 'template') {
      continue;
    }
    
    // while you have an template element
    while ($reader->localName === 'template') {
      // convert to SimpleXMLElement
      $element = simplexml_import_dom(
        // expand to a DOMElement in the prepared document object
        $reader->expand($dom)
      );
      var_dump(
        $element 
      );
      // move to the next template sibling
      $reader->next('template');
    }
    

    Output:

    object(SimpleXMLElement)#3 (1) {
      ["styles"]=>
      object(SimpleXMLElement)#4 (1) {
        ["style"]=>
        string(4) "TEST"
      }
    }
    

    I usually use DOM+Xpath and do not convert it to SimpleXML, but this approach should work fine for your problem.

    0 讨论(0)
提交回复
热议问题