【问题标题】:file_get_contents - Special characters in URL - Special casefile_get_contents - URL 中的特殊字符 - 特殊情况
【发布时间】:2015-10-21 14:42:20
【问题描述】:

在 URL 包含“Ö”字符的这种特殊情况下,我没有让 file_get_contents() 返回页面。

$url = "https://se.timeedit.net/web/liu/db1/schema/s/s.html?tab=3&object=CM_949A11_1534_1603_DAG_DST_50_ÖVRIGT_1_1&type=subgroup&startdate=20150101&enddate=20300501"
print file_get_contents($url);

如何使 file_get_contents() 在此 url 上按预期工作?

我尝试了以下解决方案,但没有奏效:

1.

print rawurlencode(utf8_encode($url));

2.

print mb_convert_encoding($url, 'HTML-ENTITIES', "UTF-8");

3.

$url = urlencode($url);
print file_get_contents($url);

4.

$content = file_get_contents($url);
print mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));

在这些问题中找到:

file_get_contents - special characters in URL

PHP get url with special characters without urlencode:ing them!

file_get_contents() Breaks Up UTF-8 Characters

更新: 如您所见,在我的示例中实际上返回了一个页面,但它不是预期的页面,是您在浏览器中键入 url 时得到的页面。

【问题讨论】:

  • 您可能想快速浏览以下链接:stackoverflow.com/questions/2236668/…
  • @HomelessPerson 正如我在问题中所写的,我已经看到了这个问题,您能否指出我的案例的相关部分?

标签: php utf-8 character-encoding file-get-contents


【解决方案1】:

网址不能包含“Ö”!从这个基本前提开始。任何不在狭窄定义的 ASCII 子集中的字符都必须经过 URL 编码才能在 URL 中表示。正确的做法是urlencode 或rawurlencode(取决于服务器期望的格式)URL 的各个部分,而不是整个 URL。

例如:

$url = sprintf('https://se.timeedit.net/web/liu/db1/schema/s/s.html?tab=3&object=%s&type=subgroup&startdate=20150101&enddate=20300501',
               rawurlencode('CM_949A11_1534_1603_DAG_DST_50_ÖVRIGT_1_1'));

您仍然需要对字符串使用正确的编码! ISO-8859-1 中的Ö 将被 URL 编码为 %D6,而在 UTF-8 中它将被编码为 %C3%96。哪一个是正确的取决于服务器的期望。

【讨论】:

    【解决方案2】:

    需要对 unicode 字符进行百分比编码。这是我知道的一种方法。

    $url2 = "https://se.timeedit.net/web/liu/db1/schema/s/s.html?tab=3&object=" . urlencode('CM_949A11_1534_1603_DAG_DST_50_ÖVRIGT_1_1') . "&type=subgroup&startdate=20150101&enddate=20300501";
    echo "encoded: " . $url2;
    print file_get_contents($url2);
    

    【讨论】:

      猜你喜欢
      • 2012-05-10
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多