友好的SEO优化
将标题在末尾进行显示,标题可用 翻译成英文或者直接以拼音的形式展现出来,例如: SEO前:http://larabbs.test/topics/119 - SEO后:http://larabbs.test/topics/119/slug-translation-test
在 App\Handlers 中创建SlugTranslateHandler.php
分别安装 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); }
}
配置相关信息
config/services.php
配置授权信息:
'baidu_translate' => [ 'appid' => env('BAIDU_TRANSLATE_APPID'), 'key' => env('BAIDU_TRANSLATE_KEY'), ],
.env
BAIDU_TRANSLATE_APPID = 20180716000185971 BAIDU_TRANSLATE_KEY = yRx9s9QAYxBiy8UuBc5Y
调用翻译 例如:
$topic->slug = app(SlugTranslateHandler::class)->translate($topic->title);
本文由 邓尘锋 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: May 4, 2019 at 11:40 am