duancuisan2503 2017-03-28 11:07
浏览 95
已采纳

加快使用PHP中的DOMDocument类和命名空间解析XML文档

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?

  • 写回答

1条回答 默认 最新

  • duanlipeng4136 2017-06-15 01:45
    关注

    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>';
            }
    
        }
    
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿请人帮写个安卓系统下禁止装软件及禁止拷入文件的程序
  • ¥100 用 H.265 对音视频硬编码 (CUDA)
  • ¥20 mpich安装完成后出问题
  • ¥15 multisim仿真
  • ¥15 stm32循迹小车代码问题
  • ¥15 输入一堆单词,使其去重输出
  • ¥15 qc代码,修改和添加东西
  • ¥50 Unity的粒子系统使用shadergraph(内置管线)制作的一个顶点偏移shader,但是粒子模型移动时,顶点也会偏移
  • ¥15 如何用python处理excel的数据(极值标准化)
  • ¥15 三向应力状态求剪应力