Speed up parsing XML documents with DOMDocument class in PHP and with namespaces -
i have 6 xml documents need parse php. every file has 50000 elements therefore need fast parser 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 come code:
$input_file=scandir($oib_path);//scanning directory files foreach ($input_file $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') $element) { echo $element->nodevalue, ', <br> '; } }
but slow takes more 20 minutes parse 6 files.
what can improve it?
xpath queries faster doing normal traversal using dom.
try below code , let me know if improves performance.
<?php $input_file=scandir($oib_path);//scanning directory files foreach ($input_file $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 $element) { echo $element->nodevalue.'<br>'; } } } ?>
Comments
Post a Comment