PHP前端开发

PHP微信开发之有道翻译实例代码

百变鹏仔 2天前 #前端问答
文章标签 实例

首先,你需要去有道翻译api官网去申请key:http://fanyi.youdao.com/openapi?path=data-mode
得到key之后,就可以开始从该api获得查询的数据了(返回json还是xml,看个人喜好,这里我用的是json) 
下面我直接把responsemsg方法里,实现翻译的代码给出。

 public function responseMsg(){    //get post data, May be due to the different environments  $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信发来的XML数据   //extract post data if(!empty($postStr)){        //解析post来的XML为一个对象$postObj   $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);      $fromUsername = $postObj-&gt;FromUserName; //请求消息的用户   $toUsername = $postObj-&gt;ToUserName; //"我"(订阅号)的公众号id   $keyword = trim($postObj-&gt;Content); //用户发给订阅号的消息内容   $time = time(); //时间戳   $msgtype = 'text'; //消息类型:文本   $textTpl = "<xml>  <tousername></tousername>  <fromusername></fromusername>  <createtime>%s</createtime>  <msgtype></msgtype>  <content></content>  </xml>";    if($postObj-&gt;MsgType == 'event'){ //如果XML信息里消息类型为event    if($postObj-&gt;Event == 'subscribe'){ //如果是订阅事件     $contentStr = "欢迎订阅misaka去年夏天!更多精彩内容:http://blog.csdn.net/misakaqunianxiatian";     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);     echo $resultStr;     exit();    }   }    $which = mb_substr($keyword, 0, 2, 'UTF-8');//获取要返回什么样的信息    if($which== "翻译"){ //如果要进行翻译    $fanyi = $which;    $search = str_replace($fanyi, '', $keyword); //要翻译的关键字     $key = ""; //在有道API申请的key    $keyfrom = ""; //与key对应    $url = 'http://fanyi.youdao.com/openapi.do?keyfrom=' . $keyfrom . '&amp;key=' . $key . '&amp;type=data&amp;doctype=json&amp;version=1.1&amp;q=' . urlencode($search);//调用有道翻译API         $json = file_get_contents($url);//也可以用curl来获取    $res = json_decode($json, true);     /**     * 以下从返回的数据中提取翻译结果     */    $contentStr = '【查询】' . $res['query'] . "";    $contentStr .= "【翻译】" . $res['translation'][0] . "";     $str = '';    foreach($res['basic']['explains'] as $v){     $str .= $v . "";    }    $contentStr .= "【基本释义】" . $str;      if(isset($res['web'])){      foreach($res['web'] as $kk=&gt;$vv){      sort($vv);      $res['web'][$kk] = $vv; //调节字段顺序     }      $str = '';     foreach($res['web'] as $v){      foreach($v as $k2=&gt;$v2){       if($k2 == 0){        $str .= "【". $v2 ."】";       }else{        foreach($v2 as $v3){         $str .= $v3 ."";        }       }      }     }     $contentStr .= "【网络释义】" . $str;         }     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);    echo $resultStr;    exit();     }

注:关注的订阅号返回的信息里要换行,要使用“”。在你的网站空间里,将你的代码修改一下,就可以给订阅号发送比如“翻译汉堡包”,订阅号会调用有道的API来返回翻译结果,可以中英文互译,也可以是句子。