Cikson
Cikson

Reputation: 108

Speed up parsing XML documents with DOMDocument class in PHP and with namespaces

I have 6 XML documents that I need to parse with PHP. Every file has 50000 elements therefore I need fast parser so I chose DOMDocument class. Example of XML file is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:PinsCountryCodeIds xmlns:ns2="http://apis-it.hr/umu/2015/types/kp">
    <ns2:PinCountryCodeId>
        <ns2:CountryCodeId>HR</ns2:CountryCodeId>
        <ns2:PinPrimatelja>000000000</ns2:PinPrimatelja>
    </ns2:PinCountryCodeId>
    <ns2:PinCountryCodeId>
        <ns2:CountryCodeId>HR</ns2:CountryCodeId>
        <ns2:PinPrimatelja>000000001</ns2:PinPrimatelja>
    </ns2:PinCountryCodeId>
    <ns2:PinCountryCodeId>
        <ns2:CountryCodeId>HR</ns2:CountryCodeId>
        <ns2:PinPrimatelja>000000002</ns2:PinPrimatelja>
    </ns2:PinCountryCodeId>
</ns2:PinsCountryCodeIds>

The best what I come up with is this code:

$input_file=scandir($OIB_path);//Scanning directory for files
foreach ($input_file as $input_name){
    if($input_name=="." || $input_name=="..")
        continue;
    $OIB_file=$OIB_path . $input_name;

    $doc = new DOMDocument();
    $doc->load( $OIB_file );

    $doc->saveXML();
    foreach ($doc->getElementsByTagNameNS('http://apis-it.hr/umu/2015/types/kp', 'PinPrimatelja') as $element) {
        echo  $element->nodeValue, ', <br> ';
    }           

}

But it is too slow it takes more then 20 minutes to parse 6 files.

What can I do to improve it?

Upvotes: 0

Views: 381

Answers (1)

Regina Hong
Regina Hong

Reputation: 98

Xpath queries are much faster than doing normal traversal using DOM.

Try below code and let me know if it improves the performance.

<?php

$input_file=scandir($OIB_path);//Scanning directory for files

foreach ($input_file as $input_name){

    if($input_name=="." || $input_name=="..")
        continue;
    $OIB_file=$OIB_path . $input_name;

    $doc = new DOMDocument();
    $doc->load( $OIB_file );

    $xpath = new DOMXPath($doc);
    $xpath->registerNameSpace('x', 'http://apis-it.hr/umu/2015/types/kp');

    $elements = $xpath->query('//x:PinCountryCodeId/x:PinPrimatelja');

    if ($elements->length > 0) {
        foreach ($elements as $element) {
            echo $element->nodeValue.'<br>';
        }

    }

}

?>

Upvotes: 1

Related Questions