php处理json码 实例:PHP实现百度翻译API调用处理

WBOY
Release: 2016-06-23 13:40:49
Original
1383 people have browsed it

今天给一个小程序写后台,通过调用百度翻译API实现翻译功能。

调用百度API的url为'http://openapi.baidu.com/public/2.0/translate/dict/simple?client_id=你的KEY&q=要查的汉语&from=zh&to=en';

申请步骤详见点击打开链接

以上是前期准备工作

===================================================================================================

通过调用百度翻译的API穿回的json为:{"errno":0,"data":{"word_name":"\u4f60\u597d","symbols":[{"ph_zh":"n\u01d0 h\u01ceo","parts":[{"part":"","means":["hello","hi","How do you do!"]}]}]},"to":"en","from":"zh"}'

这里眼力不好的同学可以格式化一下字符串

{	"errno":0,	"data":{		"word_name":"\u4f60\u597d",		"symbols":[				{"ph_zh":"n\u01d0 h\u01ceo",			"parts":[				{"part":"",				"means":[					"hello",					"hi",					"How do you do!"					]				}				]			}]		},		"to":"en",		"from":"zh"}
Copy after login

关键语句:json_decode($jsonResult)->data->symbols[0]->parts[0]

也怪我太笨了,就这么一条语句折腾了我一晚上……基础太重要了!!!

通过这一步获取到了

{"part":"",				"means":[					"hello",					"hi",					"How do you do!"					]				}
Copy after login

下一步通过
	$jsonObj->means[0]	$jsonObj->means[1]	$jsonObj->means[2]
Copy after login
分别获取“你好”的3个释义。

实际操作中可以通过循环语句获取全部的释义。

下面是全部代码

<?php $word=$_GET['s'];    $url='http://openapi.baidu.com/public/2.0/translate/dict/simple?client_id=你的KEY&q='.$word.'&from=zh&to=en';	$jsonResult=file_get_contents($url);	$jsonObj=json_decode($jsonResult)->data->symbols[0]->parts[0];	echo  $jsonObj->means[0].'<br>';	echo  $jsonObj->means[1].'<br>';	echo  $jsonObj->means[2].'<br>';?>
Copy after login
输入  url?s=你好
运行结果


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template