A
A
Alexey2020-04-29 15:26:17
Create a sitemap
Alexey, 2020-04-29 15:26:17

How to create an auto-generated sitemap on an image site?

There is a need to create a sitemap-image.xml for the images. An important detail is that it must be auto-generated. It does not matter how it will be implemented, using a js script, a task for gulp, and so on.
After several days of searching on the Internet, I did not find any solution. In most cases, almost nothing is written about this in principle.
It would be nice to see a script or maybe a link to some resource where this is normally explained.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2020-04-29
@rpsv

If you have all the statics in one directory:

Spoiler

class SitemapImageBuilder
{
  public function __construct(string $imagesDir)
  {
    $this->dir = $imagesDir;
  }

  public function run()
  {
    $imageFiles = $this->getImageFiles($this->dir);
    $this->generateXml($imageFiles);
  }

  public function getImageFiles(string $path)
  {
    $ret = [];
    $files = scandir($path);
    $explodeNames = [
      '.',
      '..',
    ];
    $mimeRe = "/^image/";
    foreach ($files as $name) {
      if (in_array($name, $explodeNames)) {
        continue;
      }

      $filePath = $path .'/'. $name;
      if (is_dir($filePath)) {
        $childs = $this->getImageFiles($filePath);
        if ($childs) {
          array_push($ret, ...$childs);
        }
      }
      else if (is_file($filePath)) {
        $mime = mime_content_type($name);
        if (preg_match($mimeRe, $mime)) {
          $ret[] = $filePath;
        }
      }
    }
    return $ret;
  }

  public function generateXml(array $pathes)
  {
    // генерация XML sitemap
  }
}

$imagesDir = 'path/to/static';
(new SitemapImageBuilder($imagesDir))->run();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question