【问题标题】:Unicode characters causing 404 error in file_get_contents()在 file_get_contents() 中导致 404 错误的 Unicode 字符
【发布时间】:2019-09-05 18:22:05
【问题描述】:

我有一个应用程序通过链接自动访问 URL。只要 URL 不包含 Unicode,它就可以正常工作。

例如,我有一个链接:

<a href="https://example.com/catalog/kraków/list.html">Kraków</a>

该链接在源代码中仅包含纯 ó 字符。当我尝试这样做时:

$href = $crawler->filter('a')->attr('href');
$html = file_get_contents($href);

返回 404 错误。如果我在浏览器中访问该 URL,那很好,因为浏览器将 ó 替换为 %C3%B3。

我应该怎么做才能通过file_get_contents()访问该URL?

【问题讨论】:

标签: php url domcrawler


【解决方案1】:

urlencode 可用于对 url 部分进行编码。以下 sn -p 提取路径 /catalog/kraków/list.html 并对内容进行编码:catalogkrakówlist.html 而不是整个 url 以保留路径。

查看以下解决方案:

function encodeUri($uri){
    $urlParts = parse_url($uri);

    $path = implode('/', array_map(function($pathPart){
        return strpos($pathPart, '%') !== false ? $pathPart : urlencode($pathPart);
    },explode('/', $urlParts['path'])));

    $query = array_key_exists('query', $urlParts) ? '?' . $urlParts['query'] : '';

    return $urlParts['scheme'] . '://' . $urlParts['host']  . $path . $query;
}


$href = $crawler->filter('a')->attr('href');
$html = file_get_contents(encodeUri($href)); // outputs: https://example.com/catalog/krak%C3%B3w/list.html

parse_url 文档:https://www.php.net/manual/en/function.parse-url.php

【讨论】:

  • 它丢失了查询字符串。我理解这个想法,我将在 URL 的路径部分实现它。
  • 更新了答案以包含查询路径:) @RoboRobok
  • 现在它会在缺少查询字符串时导致错误,并在没有查询时添加(理论上)冗余?
  • 抱歉,已修复@RoboRobok
  • 它看起来越来越好,但你知道。然后是端口等。另外,如果URL已经编码,也会造成麻烦。没有更好的办法吗?
猜你喜欢
  • 1970-01-01
  • 2019-05-13
  • 2015-02-16
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多