generate xml sitemap using php also in Laravel [ with or without laravel ] 2022

    By: Manu
    1 year ago
    Category: PHPViews: 191

    Alright in this guide we are going to see how to generate xml sitemap using php and also using laravel. So here first we are going to see using laravel.

    Generate Sitemap in Laravel

    For this we create a command using

    php artisan make:command generateSitemap
    


    this will create a file generateSitemap under "App/console/commands" here we add the command name in description also the code for generating sitemap.


    Command's signature

        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'generate:sitemap';
    


    Command's description

        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'This command generates sitemap for the website.';
    


    Login in handle function

                $posts = Post::take(2)->get();  // Taking only 2 posts. USE Post::get() TO GET ALL.
                $urls  = [];
    
    
                ini_set("memory_limit", "-1");
                set_time_limit(0);
                ini_set('max_execution_time', 0);
                ignore_user_abort(true);
    
    
                // PUTTING POSTS TO ARRAY.
    
                foreach($posts  as $post )
                {
                    $urls[] = '/post/'. $post->id. '/'. Str::slug($post->title);
                }
    
    
                // MAKEING SITEMAP FOLDER.
    
    
                if(!file_exists(public_path('/sitemap')))
                {
                    mkdir(public_path('/sitemap', 0777, true));
                }
    
    
                Header('Content-type: text/xml');
    
    
                $time = new DateTime;
                $dom  = new DOMDocument('1.0', 'UTF-8');
    
                // Main root tag.
    
                // GENERATING XML.
    
                $root = $dom->createElement('urlset');
                $dom->appendChild($root);
                $root->setAttribute('xmlns', "http://www.sitemaps.org/schemas/sitemap/0.9");
                $root->setAttribute('xmlns:xhtml', "http://www.w3.org/1999/xhtml");
                $root->setAttribute('xmlns:image', "http://www.google.com/schemas/sitemap-image/1.1");
                $root->setAttribute('xmlns:video', "http://www.google.com/schemas/sitemap-video/1.1");
    
    
                $this->path = public_path('/sitmap/');
                $fileName = 'sitemap';
    
    
                // Rename old sitemap.
    
    
                if(file_exists($this->path.$fileName.'.xml'))
                {
                    chmod($this->path, 0777);
                    chmod($this->path.$fileName.'.xml', 0777);
                    rename($this->path.$fileName.'.xml', $this->path.'sitemap-old-'.date('D_d-M-Y h-m-s').'.xml');
                }
    
    
                // PUTTING POSTS TO XML.
    
                foreach($urls as $url)
                {
                    if(isset($url))
                    {
                        $result = $dom->createElement('url');
                        $root->appendChild($result);
                        $result->appendChild($dom->createElement('loc', "https://zarx.biz". $url));
                        $result->appendChild($dom->createElement('priority', '1.0'));
                        $result->appendChild($dom->createElement('lastmod', $time->format(DateTime::ATOM)));
                        $dom->save(public_path('/sitemap/'.$fileName.'.xml'));
                    }
                }
    
    
                if(env('APP_ENV') == 'local')
                {
                    dd('Sitemap Generated');
                }
    


    Generate sitemap using PHP

    For this we add code in index.php it looks something like this, The only difference mainly is in the query when we get the "urls".

         $urls  = [];
    
    
         ini_set("memory_limit", "-1");
         set_time_limit(0);
         ini_set('max_execution_time', 0);
         ignore_user_abort(true);
    
         // QUERY.
    
         $link = mysqli_connect('127.0.0.1', 'root', '', 'test');
         $query = "SELECT * FROM posts LIMIT 2";
         $result = mysqli_query($link, $query);
    
         // PUTTING POSTS IN ARRAY.
    
         while($row = mysqli_fetch_assoc($result))
         {
           $urls[] = '/post/'. $row['id']. '/'. $this->slugify($row['title']);
         }
    
    


    Check our video guide for better understanding also download the code zip.