亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP 有沒有辦法在找到字符串匹配后停止curl 請求?

PHP 有沒有辦法在找到字符串匹配后停止curl 請求?

PHP
蝴蝶不菲 2023-06-24 15:37:50
我目前有一個 PHP 腳本,可以下載網站的 html,然后在結果preg_match上運行curl_exec()。該網頁大小約為 2 Mb,并且匹配字符串通常位于頁面開頭,因此大量的下載時間似乎是不必要的。我想知道是否有辦法在找到字符串后終止卷曲會話。管道有用嗎?我也愿意嘗試其他框架,例如 BASH 和 Javascript。謝謝。
查看完整描述

1 回答

?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

在 PHP 中,您可以使用fsockopen,然后在匹配后盡早跳出循環:

<?php

$host = "stackoverflow.com";

$page = "/questions/62504744/is-there-a-way-in-php-to-stop-a-curl-request-once-a-string-match-is-found/62505031";


$fp = fsockopen("ssl://$host", 443, $errno, $errdesc);

if (!$fp)

? ? die("Couldn't connect to $host:\nError: $errno\nDesc: $errdesc\n");

? ??

stream_set_blocking($fp, 0);


$request = "GET $page HTTP/1.1\r\n";

$request .= "Host: $host\r\n";

$request .= "User-Agent: Mozilla/5.0\r\n";

$request .= "Accept: text/xml,application/xml,application/xhtml+xml,";

$request .= "text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,";

$request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n\r\n";


fputs ($fp, $request);


$content = '';

while (!feof($fp)) {

? ? $body = fgets($fp);

? ? if (stristr($body, "PHP script that downloads a website's html")) {

? ? ? ? echo 'Was found';

? ? ? ? $content = $body;

? ? ? ? break;

? ? }

}


fclose($fp);


echo $content;


或者,如果你想使用nodejs,你也可以這樣做。


const https = require("https");


const req = https.request({

? host: "stackoverflow.com",

? port: 443,

? path:

? ? "/questions/62504744/is-there-a-way-in-php-to-stop-a-curl-request-once-a-string-match-is-found"

}, function(res) {


? let found = false;


? res.on("data", function(chunk) {

? ? // change PHP script... to DOCTYPE, which will show it aborts after first chunk

? ? if (chunk.includes("PHP script that downloads a website's html")) {

? ? ? found = true;

? ? ? req.abort();

? ? }

? ? console.log(chunk);

? });


? res.on("end", () => console.log(found));

});


req.end();

編輯:


用匹配的字符串做一些事情。


const https = require("https");


// callback function when a match is found

function doSomthing(str){

? console.log('matched partial dom:', str)

}


const req = https.request({

? host: "stackoverflow.com",

? port: 443,

? path:

? ? "/questions/62504744/is-there-a-way-in-php-to-stop-a-curl-request-once-a-string-match-is-found"

}, function(res) {

? let body = ''

? res.on("data", function(chunk) {

? ? // change PHP script... to DOCTYPE, which will show it aborts after first chunk

? ? if (chunk.includes("PHP script that downloads a website's html")) {

? ? ? body = chunk.toString();

? ? ? req.abort();

? ? }

? });


? res.on("end", () => doSomthing(body));

});


req.end();


查看完整回答
反對 回復 2023-06-24
  • 1 回答
  • 0 關注
  • 125 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號