PHP:创建动态站点地图

问题描述 投票:-1回答:1

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

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

上面的代码完美地为指定的URL生成一个站点地图但我需要一些可以循环遍历指定的URL并获取它们上的所有链接以创建单个站点地图而忽略重复链接。

php web-crawler sitemap google-webmaster-tools
1个回答
0
投票

将您的URL存储在一个数组中,然后在数组上执行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>'; 
?>
© www.soinside.com 2019 - 2024. All rights reserved.