Google Translate API v2 - 跳过单词和特殊字符

时间:2016-06-07 22:55:12

标签: php google-translate url-encoding

我试图将Google API V2与PHP一起使用

我需要排除一些字词,以便将它们包装到<span class"notranslate">WORD</span>

问题是我的文字包含一些特殊的字符,所以我使用urlencode($input)

问题是urlencode打破了排除字功能......

我做错了什么?

示例

$url = "https://www.googleapis.com/language/translate/v2";
$params = array(
    'key' => $helper->getConfigValue('google_api'),
    'source' => $from,
    'target' => $to, // NOTE for CHINESE zh-CN
    'q' => urlencode($input),
);
$url .= '?' . http_build_query($params);

$handle = curl_init($url);
....

1 个答案:

答案 0 :(得分:2)

http_build_query已经应用了url编码,因此urlencode($input)是多余的

<?php
$str = '<span class="notranslate">WORD</span>';

$params = [
    'single' => $str,
    'double' => urlencode($str)
];           
echo http_build_query($params);

结果:

single=%3Cspan+class%3D%22notranslate%22%3EWORD%3C%2Fspan%3E
double=%253Cspan%2Bclass%253D%2522notranslate%2522%253EWORD%253C%252Fspan%253E

请注意double上的双重编码。