PHP流下载网站内容,直到找到字符串
主题说明了一切。我需要启动一个网站流,并在找到例如PHP流下载网站内容,直到找到字符串,php,sockets,web,stream,download,Php,Sockets,Web,Stream,Download,主题说明了一切。我需要启动一个网站流,并在找到例如时停止它。我想这样做,以保持两端的带宽,并节省脚本运行时间 我不想将整个页面内容下载到内存中;我需要一个块来的内容流,在PHP 谢谢社区,我爱你们:) 重要提示:(感谢@GordonM) allow\u url\u fopen需要在php.ini中启用才能使用fsockopen()看起来很合理,不过您可能希望使用curl,因为我认为如果禁用allow\u url\u fopen,此方法不起作用;我在使用cURL时发现了一个答案:我在该示例中发现
时停止它。我想这样做,以保持两端的带宽,并节省脚本运行时间
我不想将整个页面内容下载到内存中;我需要一个块来的内容流,在PHP
谢谢社区,我爱你们:)
重要提示:(感谢@GordonM)
allow\u url\u fopen
需要在php.ini
中启用才能使用fsockopen()
看起来很合理,不过您可能希望使用curl,因为我认为如果禁用allow\u url\u fopen,此方法不起作用;我在使用cURL时发现了一个答案:我在该示例中发现的唯一问题是更大的CPU负载(但在罕见的请求中不太明显)。
<?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);
?>