乖兔博客

乖兔 > CMS系统 > PHP > PHP输出汉字自动转拼音和英文

PHP输出汉字自动转拼音和英文

乖兔 更新于: 2020-03-26 分类:PHP

PHP自动换汉字转拼音翻译英文.jpg

使用PHP在输出中问的时候自动输出对应的拼音和英文。原理为,英文调用百度翻译接口(需要自行申请),中可以本地化,使用拼音字库。点我下载PHP自拼音字库

汉字自动转拼音和英文的PHP代码的写法:

<?php
include('./Cn2pinyin.php');

$str="我是要输出的汉字";
$json=file_get_contents('http://openapi.baidu.com/public/2.0/bmt/translate?client_id=yourbaiduclinetid&q='.$str.'&from=auto&to=auto');
$json = stripslashes($json);
$arr=json_decode($json,true);

// 获取英文(需要在线,至于不在线,如果英文只是想作为一个标识或者索引字段的话,可以用插入id+拼音缩写构件唯一id)
echo $eng=strtolower(str_replace(' ', '_',$arr['trans_result'][0]['dst']))."<br>";

$py=new Comm_Cn2pinyin();

//获取拼音 
echo strtolower($py->getPinyin($str))."<br>";

// 获取拼音缩写
echo strtolower($py->getShortPinyin($str));
?>

以上代码经过测试,不是深度使用的话基本能满足需求。

打赏