簡體   English   中英

加快使用PHP中的DOMDocument類以及名稱空間解析XML文檔的速度

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

我有6個需要使用PHP解析的XML文檔。 每個文件有50000個元素,因此我需要快速解析器,所以我選擇了DOMDocument類。 XML文件的示例是:

<?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>

我想到的最好的是此代碼:

$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> ';
    }           

}

但是它太慢了,解析6個文件要花費超過20分鍾的時間。

我該怎么做才能改善它?

Xpath查詢比使用DOM進行普通遍歷要快得多。

嘗試下面的代碼,讓我知道它是否可以提高性能。

<?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>';
        }

    }

}

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM