如何使用php压缩站点地图

时间:2012-03-22 18:00:00

标签: php xml compression gzip sitemap

我有以下代码,它工作正常

        header ("content-type: text/xml");
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.google.com/schemas/sitepam/0.84">';
        $xml .= '<url><loc>'.SiteRoot.'</loc><changefreq>daily</changefreq><priority>1.0</priority></url>';
        $xml .= '<url><loc>'.SiteRoot.'/directory</loc><changefreq>daily</changefreq><priority>0.9</priority></url>';
        $Query = mysql_query ("SELECT link FROM `om` ORDER BY `link`");
        while($row = mysql_fetch_array($Query)) {
            $xml .= '<url>';
            $xml .= '<loc>'.GenerateLink( 'link',$row['link'] ).'</loc>';
            $xml .= '<changefreq>weekly</changefreq>';
            $xml .= '<priority>0.8</priority>';
            $xml .= '</url>';
        }
        $xml .= '</urlset>';
        echo $xml;

当我尝试用mime标头压缩它时

header('content-type: application/x-gzip');
header('Content-Disposition: attachment; filename="sitemap.xml.gz"');

浏览器下载.gz文件,但该文件未打开。 winrar给我一个错误说:存档格式未知或损坏

这是最终代码:

    //  header ("content-type: text/xml");
        header('content-type: application/x-gzip');
        header('Content-Disposition: attachment; filename="sitemap.xml.gz"');
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.google.com/schemas/sitepam/0.84">';
        $xml .= '<url><loc>'.SiteRoot.'</loc><changefreq>daily</changefreq><priority>1.0</priority></url>';
        $xml .= '<url><loc>'.SiteRoot.'/directory</loc><changefreq>daily</changefreq><priority>0.9</priority></url>';
        $Query = mysql_query ("SELECT link FROM `om` ORDER BY `link`");
        while($row = mysql_fetch_array($Query)) {
            $xml .= '<url>';
            $xml .= '<loc>'.GenerateLink( 'link',$row['link'] ).'</loc>';
            $xml .= '<changefreq>weekly</changefreq>';
            $xml .= '<priority>0.8</priority>';
            $xml .= '</url>';
        }
        $xml .= '</urlset>';
        echo $xml;

1 个答案:

答案 0 :(得分:7)

尝试使用一些内置的gzip函数,例如gzencode

echo gzencode($xml);