【问题标题】:PHP stream download website content until string foundPHP流下载网站内容,直到找到字符串
【发布时间】:2012-08-29 23:15:16
【问题描述】:

主题说明了一切。我需要启动一个网站流并在例如找到</head>。我想这样做是为了保留两端的带宽并节省脚本运行时间。

我不想将整个页面内容下载到内存中;我需要在 PHP 中以块形式出现的内容流。

感谢社区,我爱你们 :)

【问题讨论】:

    标签: php sockets web stream download


    【解决方案1】:
    <?php
    
    function streamUntilStringFound($url, $string, $timeout = 30){
    
        // remove the protocol - prevent the errors
        $url = parse_url($url);
        unset($url['scheme']);
        $url = implode("", $url);
    
        // start the stream
        $fp = @fsockopen($url, 80, $errno, $errstr, $timeout);
        if (!$fp) {
            $buffer = "Invalid URL!"; // use $errstr to show the exact error
        } else {
            $out  = "GET / HTTP/1.1\r\n";
            $out .= "Host: $url\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fwrite($fp, $out);
            $buffer = "";
            while (!feof($fp)) {
                $buffer .= fgets($fp, 128);
                // string found - stop downloading any new content
                if (strpos(strtolower($buffer), $string) !== false) break;
            }
            fclose($fp);
        }
    
        return $buffer;
    
    }
    
    // download all content until closing </head> is found
    $content = streamUntilStringFound("whoapi.com", "</head>");
    
    // show us what is found
    echo "<pre>".htmlspecialchars($content);
    
    ?>
    

    重要提示: (感谢@GordonM)

    allow_url_fopen 需要在php.ini 中启用才能使用fsockopen()

    【讨论】:

    • 看起来很合理,但您可能想改用 curl,因为我认为如果禁用了 allow_url_fopen,此方法将不起作用。
    • cURL 也不错;这是我使用 cURL 找到的答案:stackoverflow.com/questions/1342583/… 我在该示例中发现的唯一问题是更大的 CPU 负载(但在罕见的请求上并不明显)。
    猜你喜欢
    • 2012-07-20
    • 2012-06-13
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2019-10-06
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多