在不使用composer的情况下在laravel项目中生成动态站点地图

时间:2014-11-13 05:39:13

标签: php laravel-4 sitemap

我想为我的laravel项目生成Dynamic sitemap。我已经在很多网站上搜索了答案。其中一些人用作曲家描述它。我没有得到如何做到这一点。在其他一些网站中,他们编写了代码,以便在循环中从db获取URL。在我的项目数据库中,我没有保存任何网址。我的项目是医生和病人的网站。 所以有人知道怎么写php / laravel codes for dynamic sitemap generation。?

修改

我是laravel的新手,所以我对这位作曲家并不熟悉。任何人都可以告诉我,如果我从github下载laravel-sitemap-master.zip,我可以提取它并保存在我的项目目录中?如果有人请回答这个问题会非常有帮助。

3 个答案:

答案 0 :(得分:11)

将此行添加到 routes.php

Route::get('/sitemap', function()
{
   return Response::view('sitemap')->header('Content-Type', 'application/xml');
});

创建新文件 app \ Http \ Middleware \ sitemap.php

<?php namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;
use Illuminate\Contracts\Auth\Guard;

class sitemap {

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }


    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ( !$request->is("sitemap") && $request->fullUrl() != '' && $this->auth->guest() )
        {
            $aSiteMap = \Cache::get('sitemap', []);
            $changefreq = 'always';
            if ( !empty( $aSiteMap[$request->fullUrl()]['added'] ) ) {
                $aDateDiff = Carbon::createFromTimestamp( $aSiteMap[$request->fullUrl()]['added'] )->diff( Carbon::now() );
                if ( $aDateDiff->y > 0 ) {
                    $changefreq = 'yearly';
                } else if ( $aDateDiff->m > 0) {
                    $changefreq = 'monthly';
                } else if ( $aDateDiff->d > 6 ) {
                    $changefreq = 'weekly';
                } else if ( $aDateDiff->d > 0 && $aDateDiff->d < 7 ) {
                    $changefreq = 'daily';
                } else if ( $aDateDiff->h > 0 ) {
                    $changefreq = 'hourly';
                } else {
                    $changefreq = 'always';
                }
            }
            $aSiteMap[$request->fullUrl()] = [
                'added' => time(),
                'lastmod' => Carbon::now()->toIso8601String(),
                'priority' => 1 - substr_count($request->getPathInfo(), '/') / 10,
                'changefreq' => $changefreq
            ];
            \Cache::put('sitemap', $aSiteMap, 2880);
        }
        return $next($request);
    }
}

并创建新的视图文件 resources \ views \ sitemap.blade.php

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
    @foreach( Cache::get('sitemap') as $url => $params )
    <url>
        <loc>{{$url}}</loc>
        <lastmod>{{$params['lastmod']}}</lastmod>
        <changefreq>{{$params['changefreq']}}</changefreq>
        <priority>{{$params['priority']}}</priority>
    </url>
    @endforeach
</urlset>

app \ Http \ Kernel.php 文件中为受保护的$ middleware数组添加一个条目

'sitemap' => 'App\Http\Middleware\sitemap'

答案 1 :(得分:2)

检查https://github.com/RoumenDamianoff/laravel-sitemap

Laravel 4的简单站点地图生成器。

Route::get('sitemap', function(){

    // create new sitemap object
    $sitemap = App::make("sitemap");

    // set cache (key (string), duration in minutes (Carbon|Datetime|int), turn on/off (boolean))
    // by default cache is disabled
    $sitemap->setCache('laravel.sitemap', 3600);

    // check if there is cached sitemap and build new only if is not
    if (!$sitemap->isCached())
    {
         // add item to the sitemap (url, date, priority, freq)
         $sitemap->add(URL::to('/'), '2012-08-25T20:10:00+02:00', '1.0', 'daily');
         $sitemap->add(URL::to('page'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly');

         // get all posts from db
         $posts = DB::table('posts')->orderBy('created_at', 'desc')->get();

         // add every post to the sitemap
         foreach ($posts as $post)
         {
            $sitemap->add($post->slug, $post->modified, $post->priority, $post->freq);
         }
    }

    // show your sitemap (options: 'xml' (default), 'html', 'txt', 'ror-rss', 'ror-rdf')
    return $sitemap->render('xml');

});

我用过它。效果很好!

更新#1

为了清除这种困惑,我们举一个例子。

让我们说我有一个博客表格idtitleblog

我的路线为Route::get('blog/{blog}',['as' => 'blog.show', 'uses' => 'Blog@show'];

首先我将按$blogs = DB::table('blog')->get();

获取内容

$blogs将包含结果。

我将循环,

foreach($blogs as $i)
{
     $sitemap->add(route('blog.show',[$i->title]), '2014-11-11', '1.0','daily');
}

我的所有博客都添加到了网站地图中。

答案 2 :(得分:0)

laravel中用于站点地图的路线

Route::get('/sitemap.xml', 'SitemapController@index');
Route::get('/sitemap.xml/products', 'SitemapController@product');
Route::get('/sitemap.xml/FAQ', 'SitemapController@FAQ');
Route::get('/sitemap.xml/Inquiry', 'SitemapController@inquiry);

控制器方法

  public function product()
{
    $products= Product::latest()->get();
    return response ()->view ('sitemap.product', [
        'products' => $products,
    ])->header ('Content-Type', 'text/xml');
}

public function faqs()
{
    $FAQ = FAQt::active()->orderBy('updated_at', 'desc')->get();
    return response()->view('sitemap.FAQ', [
        'FAQ' => $FAQ,
    ])->header('Content-Type', 'text/xml');
}

public function inquiry()
{
    $FAQ = inquiry ::active()->orderBy('updated_at', 'desc')->get();
    return response()->view('sitemap.inquiry ', [
        'inquiry ' => $ inquiry,
    ])->header('Content-Type', 'text/xml');
}

Generate sitemap in laravel with example

相关问题