Php 如何在不保存内容的情况下搜索网页字符串?
我知道有一种方法可以做到这一点:Php 如何在不保存内容的情况下搜索网页字符串?,php,search,curl,preg-match,Php,Search,Curl,Preg Match,我知道有一种方法可以做到这一点: $url = "http://www.google.com/search?q=test"; $str = file_get_contents($url); preg_match("title/tt\d{7}?/", $str, $matches); print $matches[0]; 但这会读取整个文件,然后扫描匹配。是否有任何方法可以减少执行上述匹配过程所需的时间?如果您知道需要查看网页内部的位置(即仅前3000个字符左右),您可以使用file\u get
$url = "http://www.google.com/search?q=test";
$str = file_get_contents($url);
preg_match("title/tt\d{7}?/", $str, $matches);
print $matches[0];
但这会读取整个文件,然后扫描匹配。是否有任何方法可以减少执行上述匹配过程所需的时间?如果您知道需要查看网页内部的位置(即仅前3000个字符左右),您可以使用
file\u get\u contents
中的maxlen
参数来限制读取:
file_get_contents($url, false, NULL, -1, 3000);
更新
如果您不知道在网页中的何处查找,并且希望最小化http请求长度,我为您设计了一个很好的解决方案:))
说明:将
$step
变量设置为每次迭代读取的字节数,并将“search?q=test”
更改为所需的查询(IMDB标题,由正则表达式判断):)它将出色地完成这项工作。
您还可以在while
循环之后执行echo$str
,以查看它在找到请求的字符串之前读取了多少
我相信这就是您所寻找的。但这是未知的,我不知道它第一次匹配的位置,但我希望该过程何时停止。很抱歉回复太晚!我现在来看看:)是的,这是IMDB的标题。聪明的猜测:)谢谢!这很好用!只需要检查一下这有多高效
$url = "www.google.com";
$step = 3000;
$found = false;
$addr = gethostbyname($url);
$client = stream_socket_client("tcp://$addr:80", $errno, $errorMessage);
if ($client === false) {
throw new UnexpectedValueException("Failed to connect: $errorMessage");
}
fwrite($client, "GET /search?q=test HTTP/1.0\r\nHost: $url\r\nAccept: */*\r\n\r\n");
$str = "";
while(!feof($client)){
$str .= stream_get_contents($client, $step, -1);
if(preg_match("/tt\d{7}?/", $str, $matches)){
$found = true;
break;
}
}
fclose($client);
if($found){
echo $matches[0];
} else {
echo "not found";
}