Next Chapter: CakePHP 4: Building a RSS Feed

Creating a Sitemap for SEO

2019-05-31 06:10:36+00

I as a product owner want to have a sitemap which allows search engines to index our content in order to make it findable.

Acceptance Criteria

  • Sitemap is automatically created daily
  • Sitemap contains all links to public text entries
  • Sitemap conforms with https://www.sitemaps.org/schemas/
  • Sitemap is validated by an external public sitemap validation tool
  • Sitemap is found via a valid robots.txt

Implementation

Create a File named 'SitemapCommand.php' in src/Command with this content.

namespace App\Command;

use Cake\Console\Arguments;
use Cake\Console\Command;
use Cake\Console\ConsoleIo;

use Cake\Datasource\ConnectionManager;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;

class SitemapCommand extends Command
{
    public function execute(Arguments $args, ConsoleIo $io)
    {
       // get data from the database
       $q = "select id, to_char(modified,'YYYY-MM-DD') as mod from entry where etyp = 't'";
       $connection = ConnectionManager::get('default');
       $rset = $connection->execute($q)->fetchAll('assoc');

       $fsys = new Filesystem();
       $fname = sys_get_temp_dir(). 'sitemap.xml';

       try {
         $fsys->appendToFile($fname,'');
       } catch (IOExceptionInterface $exception) {
         echo "An error occurred while creating your directory at ".$exception->getPath();
       }
       $fsys->appendToFile($fname,'');

       $z=0;    // Counter
       foreach($rset as $irec) {
        
          $orec  = "\n" . '' . "\n";
          $orec .= '' . 'https://www.logikfabrik.com/k/entries/view/' . $irec['id'] . '' . "\n";
          $orec .= '' . $irec['mod'] . '' . "\n";
          $orec .=  '';

          try {
            $fsys->appendToFile($fname,$orec);
          } catch (IOExceptionInterface $exception) {
            echo "An error occurred while creating your directory at ".$exception->getPath();
          }
          $z++;
       }
       $io->out('Sitemap creation ended. Records written:' . $z);

       $fsys->appendToFile($fname,'');

       $fsys->rename($fname, WWW_ROOT . '/sitemap.xml');
    }
}

In order to run the command enter the following


cd homeofapp
bin/cake sitemap

Tag: digital cakephp4

Previous Chapter: CakePHP 4: Adding User Data

Next Chapter: CakePHP 4: Building a RSS Feed