-1

I was searching for a simple script to generate a dynamic sitemap when i came across what i have below:

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

The above code works perfectly to generate a sitemap for the specified urls but i need something that can loop through the specified urls and fetch all the links on them to create a single sitemap while ignoring duplicate links.

J-Alex
  • 6,881
  • 10
  • 46
  • 64

1 Answers1

0

Store your URLs in an array then do a foreach() on the array and call urlElement($value); on the value within the loop.

<?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>'; 
?>
Tom Harris
  • 243
  • 2
  • 7