Search code examples
phpurlfile-get-contentsurlencode

PHP: bad request on file_get_contents URL


here's my code:

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

I'm getting this error:

HTTP request failed! HTTP/1.0 400 Bad Request

The problem is the special characters in the URL - it works if i use the encoded URL (which i can copy/paste from the Browser)

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

I tried using urlencode() but it will encode the whole string and won't work at all:

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

So, how can i encode special characters on URLs like that?


Solution

  • You can encode only the last part of the url

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

    Or, if your $url variable changes:

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