如何在PHP中对多个字符串进行Google Translate REST API调用
我遵循的文档来自,特别是针对如何在PHP中对多个字符串进行Google Translate REST API调用,php,arrays,rest,google-translate,Php,Arrays,Rest,Google Translate,我遵循的文档来自,特别是针对translate方法,该方法接受一个或多个参数q,用于您要翻译的值,以及接受您希望翻译值的语言的参数target 我有一个PHP函数,可以调用REST API,它可以工作: function google_translate() { $api_key = 'my api key'; $url = 'https://translation.googleapis.com/language/translate/v2?key=' . $api_key;
translate
方法,该方法接受一个或多个参数q
,用于您要翻译的值,以及接受您希望翻译值的语言的参数target
我有一个PHP函数,可以调用REST API,它可以工作:
function google_translate() {
$api_key = 'my api key';
$url = 'https://translation.googleapis.com/language/translate/v2?key=' . $api_key;
$form = [
'q' => 'Hello World!',
'target' => 'fr',
];
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $form );
$response = curl_exec( $ch );
curl_close( $ch );
$response = json_decode( $response );
var_dump( $response );
}
google_translate();
这很好,但是,文档说明,您可以通过简单地使用多个q
参数来提供额外的字符串。我在REST客户机上尝试过这一点,没有使用PHP,它可以工作,即在同一个调用中提供多个q
参数,使用不同的字符串值,并返回所有的翻译,但是,我不知道如何使用PHP实现这一点,因为PHP数组只能包含唯一的键
我如何重新编写我的函数,以便只需进行一次调用,而不是多次调用字符串转换?感谢您的帮助 您是否尝试过在querystring中添加q
<?php
$apiKey = 'Moo!';
$text = 'Hello world!';
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=fr';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
echo 'Source: ' . $text . '<br>';
echo 'Translation: ' . $responseDecoded['data']['translations'][0]['translatedText'];
您尝试过在querystring中添加q吗
<?php
$apiKey = 'Moo!';
$text = 'Hello world!';
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=fr';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
echo 'Source: ' . $text . '<br>';
echo 'Translation: ' . $responseDecoded['data']['translations'][0]['translatedText'];