SEO的优化处理?

in Laravel with 0 comment

友好的SEO优化

将标题在末尾进行显示,标题可用 翻译成英文或者直接以拼音的形式展现出来,例如: SEO前:http://larabbs.test/topics/119 - SEO后:http://larabbs.test/topics/119/slug-translation-test

  1. 在 App\Handlers 中创建SlugTranslateHandler.php

  2. 分别安装 Guzzle 和 pinyin 两个类库

    composer require "guzzlehttp/guzzle:~6.3"

    composer require "overtrue/pinyin:~3.0"

    namespace App\Handlers; use GuzzleHttp\Client; use Overtrue\Pinyin\Pinyin;

    class SlugTranslateHandler { public function translate( $title = '') { $client = new Client(); $app_id = config('services.baidu_translate.appid'); $key = config('services.baidu_translate.key');

    	$salt = time();
    	$api = 'http://api.fanyi.baidu.com/api/trans/vip/translate?';
    
    	if( empty($app_id) && empty($key) ){
    		return $this->pinyin( $title );
    	}
    	$sign = md5($app_id.$title.$salt.$key);
    	$query = http_build_query([
    		'q' => $title,
    		'from' => 'zh',
    		'to'   => 'en',
    		'appid'=>$app_id,
    		'salt' => $salt,
    		'sign' => $sign
    	]);
    
    	$response = $client->get($api.$query);
    

    // array:3 [▼ // "from" => "en" // "to" => "zh" // "trans_result" => array:1 [▼ // 0 => array:2 [▼ // "src" => "english" // "dst" => "英语" // ] // ] // ]

    	$result = json_decode($response->getBody(), true);
    	var_dump($result['trans_result'][0]['dst']);
    
    	if( isset($result['trans_result'][0]['dst']) ){
    		return str_slug( $result['trans_result'][0]['dst'] );
    	}else{
    		return $this->pinyin( $title );
    	}
    
    }
    
    public function pinyin($title)
    {
    	$pinyin = new Pinyin();
    
    	return $pinyin->permalink($title);
    }
    

    }

配置相关信息

  1. config/services.php

    配置授权信息:

    'baidu_translate' => [ 'appid' => env('BAIDU_TRANSLATE_APPID'), 'key' => env('BAIDU_TRANSLATE_KEY'), ],

  2. .env

    BAIDU_TRANSLATE_APPID = 20180716000185971 BAIDU_TRANSLATE_KEY = yRx9s9QAYxBiy8UuBc5Y

  3. 调用翻译 例如:

    $topic->slug = app(SlugTranslateHandler::class)->translate($topic->title);

Comments are closed.