PHP:创建动态站点地图

时间:2017-05-28 22:09:36

标签: php web-crawler sitemap google-webmaster-tools

当我遇到下面的内容时,我正在寻找一个简单的脚本来生成动态站点地图:

<?php 
    header("Content-Type: application/xml; charset=utf-8"); 
    echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL; 
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' .PHP_EOL; 

    function urlElement($url) {
        echo '<url>'.PHP_EOL; 
        echo '<loc>'.$url.'</loc>'. PHP_EOL; 
        echo '<changefreq>weekly</changefreq>'.PHP_EOL; 
        echo '</url>'.PHP_EOL;
    } 

    urlElement('https://www.example.com/sub1'); 
    urlElement('https://www.example.com/sub2'); 
    urlElement('https://www.example.com/sub2'); 
    echo '</urlset>'; 
?>

上面的代码非常适合为指定的网址生成站点地图,但我需要能够循环显示指定网址的内容并获取其上的所有链接以创建单个站点地图,同时忽略重复的链接。

1 个答案:

答案 0 :(得分:0)

将您的网址存储在数组中,然后对数组执行foreach()并调用urlElement($ value);关于循环内的值。

<?php 

    function urlElement($url) {
        echo '<url>'.PHP_EOL; 
        echo '<loc>'.$url.'</loc>'. PHP_EOL; 
        echo '<changefreq>weekly</changefreq>'.PHP_EOL; 
        echo '</url>'.PHP_EOL;
    }

    $urls = array(
        "http://www.google.com",
        "http://www.google.com/images",
        "http://www.google.com/maps"
    );



    header("Content-Type: application/xml; charset=utf-8"); 
    echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL; 
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' .PHP_EOL; 

    foreach($urls as $value) {
        urlElement($value);
    }

    echo '</urlset>'; 
?>