如何在PHP

时间:2015-11-03 10:12:46

标签: php arrays loops foreach domdocument

我通过DOMDocument从外部xml文件加载25000个项目(每个站点地图5000个),循环中循环显示5个站点地图需要大约15-20秒,这很多

我很担心我在循环中做错了什么。

如果有什么东西导致加载花了这么长时间,你能检查代码吗?

我不知道。

代码:

$resultHTML = '';

$sitemaps = [
    '0' => 'http://example.com/sitemap_part1.xml',
    '1' => 'http://example.com/sitemap_part2.xml',
    '2' => 'http://example.com/sitemap_part3.xml',
    '3' => 'http://example.com/sitemap_part4.xml',
    '4' => 'http://example.com/sitemap_part5.xml',
];

foreach ( $sitemaps as $sm ) :

        $DomDocument = new DOMDocument();
        $DomDocument->preserveWhiteSpace = false;
        $DomDocument->load($sm);
        $DomNodeList = $DomDocument->getElementsByTagName('loc');

        foreach($DomNodeList as $url) : 

            //$i++;

            $resultHTML .= '<div class="xml-item">';  
                $resultHTML .= $url->nodeValue;
            $resultHTML .= '</div>';

        endforeach;

endforeach;

echo $resultHTML;

1 个答案:

答案 0 :(得分:2)

这是一个未经测试的示例,小文件缓存如何工作。 你应该添加一些错误处理,但我认为它会起作用。

已更新: file_put_contents( $filepath, $resultHTML );

处的固定变量名称
$resultHTML = '';

$chacheDir = "cache";// path/to/your/cachedir
$cacheTime = 24 * 60 * 60;// 24 hours

$sitemaps = [
    '0' => 'http://example.com/sitemap_part1.xml',
    '1' => 'http://example.com/sitemap_part2.xml',
    '2' => 'http://example.com/sitemap_part3.xml',
    '3' => 'http://example.com/sitemap_part4.xml',
    '4' => 'http://example.com/sitemap_part5.xml',
];

foreach ( $sitemaps as $sm ) :
    $filepath = $chacheDir.'/'.md5( $sm );

    // check if cached file exists, and if it's too old already
    if( file_exists( $filepath ) && ( ( time() - filemtime( $filepath ) ) <= $cacheTime ) ) {
        // read from cache
        $resultHTML .= file_get_contents( $filepath );
    } else {
        //create cache file
        $DomDocument = new DOMDocument();
        $DomDocument->preserveWhiteSpace = false;
        //$DomDocument->load($sitemap_url);
        $DomDocument->load( $sm );
        $DomNodeList = $DomDocument->getElementsByTagName( 'loc' );

        foreach ( $DomNodeList as $url ) :

            //$i++;

            $resultHTML .= '<div class="xml-item">';
            $resultHTML .= $url->nodeValue;
            $resultHTML .= '</div>';

        endforeach;
        file_put_contents( $filepath, $resultHTML );
    }

endforeach;

echo $resultHTML;