【问题标题】:How do retrieve a URL protocol ("http" or "https")?如何检索 URL 协议(“http”或“https”)?
【发布时间】:2011-08-26 00:42:04
【问题描述】:

我正在使用 PHP lib Simple HTML Dom Parser,按照此处的建议 (How do you parse and process HTML/XML in PHP?) 来解析网页的 html 内容。

要创建 DOM,我必须这样做:

$html = file_get_html('http://www.example.com/');

问题是,如果我这样做:

$html = file_get_html('www.example.com');

如果不指定 URL 的协议,我会得到一个错误。

我的问题是: 我如何才能知道带有协议的 URL 是“http://www.example.com/”还是“https://www.example.com/”,只有字符串“www.example.com”?

【问题讨论】:

  • 好吧,你不能。域名完全独立于所使用的协议——也可能是ftp://,或者更奇特的东西。 (至于错误:它正在尝试打开一个名为 www.example.com 的本地文件 - 您的磁盘上可能没有该文件 :))

标签: php


【解决方案1】:

我想不出比默认“http://”更聪明的方法,如果失败,请尝试“https://”

if (!$html = file_get_html('http://' . $url)) $html = file_get_html('https://' . $url);

【讨论】:

    【解决方案2】:

    没有办法知道,因为两者都可能有效。我会假设 http://,因为通常的做法是在需要时将 http 重定向到 https,而 file_get_html 应该遵循 HTTP 301 或 302 重定向。

    【讨论】:

      【解决方案3】:

      您可以尝试在 http 地址上使用 get_headers() 并在标头中查找 Upgrade: 请求。如果得到有效响应,请使用 http。否则,请尝试 https。

      【讨论】:

        猜你喜欢
        • 2015-08-05
        • 1970-01-01
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        • 2011-05-29
        • 1970-01-01
        • 2022-12-20
        相关资源
        最近更新 更多