Dig*_*nja 2 php file-get-contents
我需要从瑞典字母中获取一些包含某些字符的URL。
如果您以这样的字符串作为示例,https://en.wikipedia.org/wiki/Åland_Islands则将其file_get_contents作为参数直接传递给调用即可。但是,如果您首先运行该URL urlencode,则调用将失败,并显示以下消息:
无法打开流:没有这样的文件或目录
尽管有文档file_get_contents说:
注意:如果要使用特殊字符(例如空格)打开URI,则需要使用urlencode()对URI进行编码。
因此,例如,如果您运行以下代码:
error_reporting(E_ALL);
ini_set("display_errors", true);
$url = urlencode("https://en.wikipedia.org/wiki/Åland_Islands");
$response = file_get_contents($url);
if($response === false) {
die('file get contents has failed');
}
echo $response;
Run Code Online (Sandbox Code Playgroud)
您将收到错误。如果您只是从代码中删除“ urlencode”,它将正常运行。
我面临的问题是URL中有一个参数是从提交的表单中获取的。而且由于PHP始终通过来运行提交的值urlencode,所以我构造的URL中的瑞典语字符将导致发生错误。
我该如何解决?
该问题可能是由于urlencode逃避了您的协议:
https://en.wikipedia.org/wiki/Åland_Islands
https%3A%2F%2Fen.wikipedia.org%2Fwiki%2F%C3%85land_Islands
Run Code Online (Sandbox Code Playgroud)
这也是我也面临的一个问题,只能通过尝试将转义的目标仅指定为逃生所需的内容来解决:
https://en.wikipedia.org/wiki/Åland_Islands
https://en.wikipedia.org/wiki/%C3%85land_Islands
Run Code Online (Sandbox Code Playgroud)
可以想象,根据角色的位置,这很棘手。我通常选择编码补丁解决方案,但与我一起工作的某些人更喜欢仅对网址的动态段进行编码。
这是我的方法:
https://en.wikipedia.org/wiki/Åland_Islands
https%3A%2F%2Fen.wikipedia.org%2Fwiki%2F%C3%85land_Islands
https://en.wikipedia.org/wiki/%C3%85land_Islands
Run Code Online (Sandbox Code Playgroud)
码:
$url = 'https://en.wikipedia.org/wiki/Åland_Islands';
$encodedUrl = urlencode($url);
$fixedEncodedUrl = str_replace(['%2F', '%3A'], ['/', ':'], $encodedUrl);
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。