所以我目前正在使用 PHP 使用 Wunderground API。但是,我似乎遇到了一些障碍。我在一个名为 Keys.txt 的文本文件中存储了几个 Wunderground API 密钥。然后我想检索每个所说的键并将它们存储到一个字符串数组中,然后我可以在其中引用它们以创建一个完整的 URL,该 URL 最终将用于进行调用和检索数据。下面是我的代码:
<?php
// This retrieves my Wunderground keys.
$keys = file_get_contents('Keys.txt');
/* This splits the keys properly into an array.
* While I don't understand why, the first element,
* equating to the first line, always returns "ÿþ",
* but otherwise, the array is stored just fine.
* This is an example of what the array will look
* like if I have stored 2 keys:
*
* [0] "ÿþ"
* [1] "0aa00aa0000aa0aa"
* [2] "1bb1b1b11bbbb1bb"
*
* According to var_dump(), each of these are
* strings.
*/
$apiKey = explode(",", $keys);
/* This concatenates everything together to form
* the full URL used to make the call to
* Wunderground and retrieve the current weather
* alerts of the area. Notice I am using in the
* first key, e.g. "0aa00aa0000aa0aa", which is
* contained in apiKey's second element (apiKey[1])
* which, according to var_dump() is indeed a string
* variable. That said, this all is stored together
* into the string variable, URLWithVar, which should
* then look like this:
*
* "http://api.wunderground.com/api/0aa00aa0000aa0aa/alerts/q/34.933889,-103.760556.json"
*/
$URLWithVar = 'http://api.wunderground.com/api/' .
$apiKey[1] .
'/alerts/q/34.933889,-103.760556.json';
/* Just for giggles, I'll also use those weird
* characters, "ÿþ", in the first element, too.
* This variable should now look like this:
*
* http://api.wunderground.com/api/ÿþ/alerts/q/34.933889,-103.760556.json
*/
$BadURL = 'http://api.wunderground.com/api/' .
$apiKey[0] .
'/alerts/q/34.933889,-103.760556.json';
/* For testing purposes, I'm going to also store
* another string variable, but this time without
* referencing the string variable that's holding the
* key.
*/
$URLWithoutVar = "http://api.wunderground.com/api/0aa00aa0000aa0aa/alerts/q/34.933889,-103.760556.json"
/* This errors with the following error:
* Warning: file_get_contents() expects parameter 1 to be a valid path, string given in D:\Program Files\xampp\htdocs\Structures\test.php on line 59
*/
$alertDataWithVar = file_get_contents($URLWithVar);
// This works properly.
$alertDataWithoutVar = file_get_contents($URLWithoutVar);
/* Interestingly, the URL with the "ÿþ" characters
* by using apiKey[0] *does* work, though not
* surprisingly, it only returns Wunderground's
* own response stating that it was an invalid key.
* But unlike the first attempt at the call with
* the real key, this does not truly error, and
* still calls Wunderground and stores the response
* it gets from Wunderground.
*/
$alertDataWithBadURL = file_get_contents($BadURL);
?>
如您所见,它似乎将我的密钥存储为字符串的方式似乎在下一个 file_get_contents() 调用中使用了扳手。因为如果我只是将密钥插入一个长字符串,它就可以工作,如果我引用包含奇怪的“ÿþ”字符的第一个元素,它也可以工作。只有当我尝试使用从 Keys.txt 文件中检索到的密钥时才会出错。是的,我已经尝试将所有内容显式转换为字符串,但我仍然得到完全相同的结果。关于如何解决这个问题的任何想法?