【问题标题】:PHP: bad request on file_get_contents URLPHP:对 file_get_contents URL 的错误请求
【发布时间】:2020-07-05 01:51:46
【问题描述】:

这是我的代码:

$url = "https://de.wikipedia.org/wiki/Creed_–_Rocky’s_Legacy";
$html = file_get_contents($url);

我收到此错误:

HTTP request failed! HTTP/1.0 400 Bad Request

问题是 URL 中的特殊字符 - 如果我使用编码的 URL(我可以从浏览器复制/粘贴)它就可以工作

https://de.wikipedia.org/wiki/Creed_%E2%80%93_Rocky%E2%80%99s_Legacy

我尝试使用urlencode(),但它会编码整个字符串并且根本不起作用:

https%3A%2F%2Fde.wikipedia.org%2Fwiki%2FCreed_%96_Rocky%92s_Legacy

那么,我怎样才能在这样的 URL 上编码特殊字符?

【问题讨论】:

  • 您的代码在这里有效。您是从 cli 还是 http 服务器运行?哪个php版本?另外,你的文件的编码和默认的php编码是什么?

标签: php url file-get-contents urlencode


【解决方案1】:

您只能对网址的最后一部分进行编码

$url = "https://de.wikipedia.org/wiki/" . urlencode("Creed_–_Rocky’s_Legacy");
$html = file_get_contents($url);

或者,如果您的 $url 变量发生变化:

$url = "https://de.wikipedia.org/wiki/Creed_–_Rocky’s_Legacy";
$html = file_get_contents(dirname($url) . "/" . urlencode(basename($url)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2014-10-24
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多