对于一个课堂项目,我们应该从另一个网站提取数据。我从 GiantBomb.com 选择了与给定游戏类似的游戏(在我的脚本中给出了它们的学分)
// $gameLink = "/call-of-duty-black-ops/61-26423/";
$html = file_get_contents("http://www.giantbomb.com" . urlencode($gameLink) . "games_similar/");
echo $html;
这不会返回任何内容。
但是,如果手动输入$gameLink:
$html = file_get_contents("http://www.giantbomb.com/call-of-duty-black-ops/61-26423/games_similar/");
echo $html;
现在,它将正确返回结果。我的代码有什么问题吗?我尝试在整个链接上执行
urlencode()
而不仅仅是 $gameLink 变量,但它仍然失败。有人有什么建议吗?
您只需对嵌入 html 中的链接进行 urlencode 即可。不要对传递给 file_get_contents() 的链接进行 urlencode。
我认为这是因为 urlencode() 对除 -_ 之外的所有非字母数字字符进行编码。
这意味着您的正斜杠被编码为 %2F,这不是您想要的;)但是,正如 hegemon 上面提到的,不要对传递给 file_get_contents() 的链接进行 urlencode。