当前位置:首页 > PHP > 正文内容

php如何将curl请求内容流式返回

高老师2年前 (2024-05-19)PHP433

应用场景:客户调用服务端,服务器端stream方式调用ai接口,服务器端stream方式返回给客户端,全程sse支持。

代码参考:

/**
 * 通过Curl+Stream方式提交数据
 *
 * @param string $url
 * @param null $header
 * @param null $data
 * @param Closure $closure
 * @throws
 */
function curlWithStream(string $url, $header = null, $data = null, $closure)
{
    if (!($closure instanceof Closure)) {
        throw new \think\Exception('closure must instanceof Closure');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
    curl_setopt($ch, CURLOPT_TCP_KEEPALIVE, 1);
    curl_setopt($ch, CURLOPT_TCP_KEEPIDLE, 120);
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $str) use ($closure) {
        return $closure($ch, $str);
    });
    curl_exec($ch);
    curl_close($ch);
}

调用例子:

curlWithStream('参数1','参数2','参数3',function($ch, $str){
	return strlen($str);
});

扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/765.html

分享给朋友:

“php如何将curl请求内容流式返回” 的相关文章

PHP异常处理,PHP自定义错误,PHP记录错误日志

PHP异常处理,PHP自定义错误,PHP记录错误日志

面试中PHP面试官会问调用一个不存在的方法,如何知道是哪个文件哪行调用的?假设方法是getWorkLoad()回答1:开启PHP错误输出,PHP会输出Fatal error: Call to undefined function getWorkLoad() in D:\wwwroot\thinkpa...

swoole中的worker_num和task_worker_num

swoole中的worker_num和task_worker_num

(1)swoole启动的主进程是master进程负责全局管理,然后master进程会再fork一个manager进程。(2)manager进程开始统一管理进程创建回收管理。(3)manager进程根据设置的worker_num和task_worker_num来创建work进程和task进程因此启动s...

php  while  true  cpu占用100%

php while true cpu占用100%

在编写多进程的实例中我在每个进程中使用如下代码://调用等待信号的处理器 while (true) {     pcntl_signal_dispatch(); }开启5个进程,cpu直接100%修正之后的代码://调用等待信号的处理器 while&...

PHP最快方式模拟curl,PHP最快爬虫模拟方法

PHP最快方式模拟curl,PHP最快爬虫模拟方法

有时候我们需要爬一个接口,但是这个接口需要很多参数,包括header和cookie要去编写,使用php curl模拟实在太慢。我们可以通过浏览器的network来复制请求为curl命令。例如我需要模拟请求接口地址:https://www.xkmz.cc/Ajax/Debug/delly,我们只需要在...

thinkphp3定时任务,tp定时任务,thinkphp定时任务

thinkphp3定时任务,tp定时任务,thinkphp定时任务

本教程使用的定时任务基于EasyTak,EasyTask官方文档:https://gitee.com/392223903/EasyTask由于tp3.2.x官方开发未考虑命令行支持和绝对路径开发的标准,因此我编写了一个支持的类来运行。1.在tp3.2.3根目录下安装easytaskcomposer&...

php中0和字符串比较时注意的问题

php中0和字符串比较时注意的问题

在正式介绍前先抛出一段代码:<?php //输入的密码 $password = empty($_POST['password']) ? 0 : $_POST['password']; //设置的密码...