php汉字转拼音 php 汉字取首字母

php汉字转拼音 php 汉字取首字母

<?php

/**
 * Class ConvertToPingYin
 *
 * 请到对应的网站申请转换接口
 *
 * https://www.showapi.com/api/lookPoint/99
 */
class ConvertToPingYin
{

    public function cpingyin($str)
    {
        //md5签名方式--非简单签名
        header("Content-Type:text/html;charset=UTF-8");
        date_default_timezone_set("PRC");
        $showapi_appid = '9918125';  //替换此值,在官网的"我的应用"中找到相关值   这个不能用自已去申请99
        $showapi_secret = '99674547fde6b6497d94cbeb2e4200ebe2';  //替换此值,在官网的"我的应用"中找到相关值 这个不能用自已去申请99
        $paramArr = array(
            'showapi_appid' => $showapi_appid,
            'content' => $str,
            'showapi_timestamp' => date("YmdHis")
        );

        $param = $this->createParam($paramArr, $showapi_secret);
        $url = 'http://route.showapi.com/99-38?' . $param;
        //  echo $url;
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        if (!isset($pinyinarr['showapi_res_body']['data'])) {
            sleep(1); //循环时怕被封
        }
        return $result;


    }

    public function createParam($paramArr, $showapi_secret)
    {
        $paraStr = "";
        $signStr = "";
        ksort($paramArr);
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $signStr .= $key . $val;
                $paraStr .= $key . '=' . urlencode($val) . '&';
            }
        }
        $signStr .= $showapi_secret;//排序好的参数加上secret,进行md5
        $sign = strtolower(md5($signStr));
        $paraStr .= 'showapi_sign=' . $sign;//md5后的值作为参数,便于服务器的效验
        // echo "排序好的参数:" . $paraStr . "<br>";
        return $paraStr;
    }
}

$pingYin = new ConvertToPingYin();
$pinyinarr = $pingYin->cpingyin('中文');

if (isset($pinyinarr['showapi_res_body']['data'])) {
    $pinyin = $pinyinarr['showapi_res_body']['data']; //取得拼音
    $initials = strtoupper(substr($pinyin, 0, 1));  //取得首字母
}

var_dump($pinyinarr);

猜你喜欢

转载自blog.csdn.net/coolpan123/article/details/80333970