0

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

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

谢谢社区,我爱你们:)

4

1 回答 1

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()

于 2012-09-05T09:08:03.473 回答