1. 程式人生 > >laravel sitemap.xml生成

laravel sitemap.xml生成

sitemap.xml格式

 <?xml version="1.0" encoding="UTF-8"?>

<urlset>
	<url>
	  <loc>http://www.example.com/</loc>
	  <lastmod>2010-01-01</lastmod>
	  <changefreq>always</changefreq>
	  <priority>1.0</priority>
	</url>

	<url>
	  <loc>http://www.example.com/1.html</loc>
	  <lastmod>2010-02-14</lastmod>
	  <changefreq>weekly</changefreq>
	  <priority>0.8</priority>
	</url>
</urlset>


 

class SitemapController extends ApplicationController
{
  public function index() {
    $xml = $this->sitemap();
    $file = fopen('sitemap.xml', 'w');
    fwrite($file, $xml);
    fclose($file);
    return redirect()->action('[email protected]')->with('success', __('common.success'));
  }

  private function sitemap() {
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    $xml .= '<urlset>';

    // 文章分類
    $categories = Category::all();
    foreach($categories as $data) {
      $xml .= $this->execute_xml('articles/'.$data->id);
    }
    // 文章
    Article::chunk(500, function($articles) use(&$xml) {
      foreach($articles as $data) {
        $xml .= $this->execute_xml('article/'.$data->id);
      }
    });

    $xml .= '</urlset>';
    return $xml;
  }


  private function execute_xml($url) {
    $xml_url = '<url>';
    $xml_url .= '<loc>'. config('app.url') . $url .'</loc>';
    $xml_url .= '<lastmod>'. date("Y-m-d", time()) .'</lastmod>';
    $xml_url .= '<changefreq>weekly</changefreq>';
    $xml_url .= '<priority>0.8</priority>';
    $xml_url .= '</url>';
    return $xml_url;
  }

}