与变量连接时,无法在 PHP 中正确形成 URL


Cannot form URL in PHP correctly when concatenated with variable

我正在尝试连接一个变量和一个字符串以形成一个将用于形成JSON对象的URL。但是,尽管我收到有效的 JSON 响应(使用 Wordreference API),因为 URL 在连接变量的地方必须不正确。

例如,带有 URL 的响应http://api.wordreference.com/[APIKEY]/json/enfr/language

{ "Error" : "NoTranslation", "Note" : "No translation was found for language'_'_.'nAucune traduction trouvée pour language'_'_.'n" }

应该有一个有效的响应,它

告诉我这个词不存在,即使它看起来 url 格式正确并且单词是有效的,如果我在浏览器中输入 URL,我会得到一个有效的响应。

我认为这与language'_'_.末尾的字符有关,其中正常的错误响应(例如,随机无效单词"qwerty")为:

{
    "Error" : "NoTranslation", 
    "Note" : "No translation was found for qweryty.'nAucune traduction trouvée pour qweryty."
}

最后的字符只是qweryty.'n

我使用的代码是:

$words = file("words.txt")[rand(0, 5449)];
$url = "http://api.wordreference.com/[APIKEY]/json/enfr/$words";
//I have also tried using $url = "http://api.wordreference.com/[APIKEY]/json/enfr/" . $words";
echo $url .  "<br/>";
$json = file_get_contents($url);
echo $json;

PHP 输出为:

 http://api.wordreference.com/5d422/json/enfr/language
{ "Error" : "NoTranslation", "Note" : "No translation was found for language'_'_.'nAucune traduction trouvée pour language'_'_." } 

(这句话.txt来自 http://dictionary-thesaurus.com/wordlists/Nouns%285,449%29.txt)
注:注:我还有一个有效的 api 密钥,我刚刚在这里订阅了 [APIKEY] 来回答这个问题。

引用: http://www.w3schools.com/php/func_filesystem_file.asp 每个数组元素都包含文件中的一行,仍然附加换行符。

您需要从请求末尾修剪换行符。

$words = str_replace(array("'r", "'n"), '', file("words.txt")[rand(0, 5449)]);