当url有空格时,file_get_contents为false(编码所有内容都不起作用)

Mat*_*ira 4 php urlencode file-get-contents

所以,问题出在这一行

$imageString = file_get_contents($image_url);
Run Code Online (Sandbox Code Playgroud)

有空格字符的网址不起作用.但是,如果我做

$imageString = file_get_contents(urlencode($image_url));
Run Code Online (Sandbox Code Playgroud)

什么都行不通.我一直在变量中收到假.

ulr是那种:

https://s3-eu-central-1.amazonaws.com/images/12/Screenshot from 2016-04-28 18 15:54:20.png
Run Code Online (Sandbox Code Playgroud)

Akr*_*hid 10

使用此功能

function escapefile_url($url){
  $parts = parse_url($url);
  $path_parts = array_map('rawurldecode', explode('/', $parts['path']));

  return
    $parts['scheme'] . '://' .
    $parts['host'] .
    implode('/', array_map('rawurlencode', $path_parts))
  ;
}


echo escapefile_url("http://example.com/foo/bar bof/some file.jpg") . "\n";
echo escapefile_url("http://example.com/foo/bar+bof/some+file.jpg") . "\n";
echo escapefile_url("http://example.com/foo/bar%20bof/some%20file.jpg") . "\n";
Run Code Online (Sandbox Code Playgroud)


小智 1

我遇到了同样的问题,如果你搜索它,你会看到所有人告诉你使用urlencode(),但是没有!urlencode()在这种情况下不起作用......

我使用了@Akram Wahid答案,效果非常好,所以我建议将其用于 file_get_contents()。

如果你想知道escapefile_url()@Akram Wahid中的作用,这里很少解释:

只需将 url 分解为数组,然后使用rawurlencode()对包含特殊字符的所有部分进行编码,而无需主域,例如(http://example.com)。

那有什么好尊重的?!这里的例子使用 urlencode()escapefile_url()来澄清这一点

echo escapefile_url("http://example.com/foo/bar bof/some file.jpg") . "<br>";
// http://example.com/foo/bar%20bof/some%20file.jpg

echo urlencode("http://example.com/foo/bar bof/some file.jpg") . "<br>";
// http%3A%2F%2Fexample.com%2Ffoo%2Fbar+bof%2Fsome+file.jpg
Run Code Online (Sandbox Code Playgroud)