【问题标题】:PHP curl to display output for URL like 'HTTP/1.1 200 OK'PHP curl 显示 URL 的输出,例如“HTTP/1.1 200 OK”
【发布时间】:2018-09-21 15:37:35
【问题描述】:

我正在尝试获取响应/状态代码,包括多个 URL 的标头。我的第一次尝试成功获得了状态码,即 200 或 301 或 302。但我希望输出类似于 HTTP/1.1 200 OK 或 HTTP/1.1 302 Found 等。

下面是我的代码,其中我只得到响应代码,即200 或301.

<?php
$line = "https://www.pnc.com";
        $ch = curl_init($line);
        curl_setopt($ch, CURLOPT_URL, $line);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER,true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_TIMEOUT,10);
        $out = curl_exec($ch);
        $ret = true;
        if ($out !== false) {
                $statuscode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
                echo "Response Code:" .$statuscode. "\r";
        }
        curl_close($ch);
?>

实际输出

Response Code:HTTP/1.1 200 OK
ETag: "846caf551746b12e876c0bad5a50830d:1475788950"
Last-Modified: Thu, 06 Oct 2016 21:22:30 GMT
Accept-Ranges: bytes
Content-Length: 17609
Content-Type: text/html
Expires: Fri, 21 Sep 2018 15:35:01 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Fri, 21 Sep 2018 15:35:01 GMT
Connection: keep-alive

预期输出

HTTP/1.1 200 OK.

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: php http curl


    【解决方案1】:

    这可以使用strtok来完成

    例子:

    $statuscode = strtok( $statuscode, "\n" );
    

    -或-

    使用explode 非常标准:

    $statuscode = explode( "\n", $statuscode )[0];
    

    当然还有其他方法

    但最简洁的方法可能是使用 cURL 本身:

    $response = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
    

    【讨论】:

    • 我使用了这个,但没有得到想要的结果。另外,我正在尝试对值进行硬编码,因此我正在使用 switch。但还是没有结果。
    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2018-09-11
    • 2016-04-07
    • 2012-03-07
    • 1970-01-01
    • 2015-01-04
    • 2020-11-04
    相关资源
    最近更新 更多