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

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

高老师10个月前 (05-19)PHP233

应用场景:客户调用服务端,服务器端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     $a=0.5*100;     if(is_int($a)){   echo'int'; } else{ echo'not int';   }    ...

xmlrpc  php,php通过xml-rpc进行通信

xmlrpc php,php通过xml-rpc进行通信

xmlrpc协议是通过http请求xml数据进行通信。webservice中和它相同的是soap。soap调用的确很简单,但是创建wsdl太繁琐,效率低下。xmlrpc很好的解决这个问题。(1).创建xmlrpc服务端(求和函数api)function getSum($method,$ar...

php生成器yield from详解

php生成器yield from详解

PHP7中,通过生成器委托(yield from),可以将其他生成器、可迭代的对象、数组委托给外层生成器。外层的生成器会先顺序 yield 委托出来的值,然后继续 yield 本身中定义的值。同时yield from也能获取到生成器的返回值...

 thinkphp5定时任务,tp5定时任务,thinkphp定时任务,php定时任务,php定时器

thinkphp5定时任务,tp5定时任务,thinkphp定时任务,php定时任务,php定时器

本教程使用的定时任务基于EasyTak,EasyTask官方文档:https://gitee.com/392223903/EasyTask(1).安装tp5.0或者5.1composer create-project topthink/think=5.0.* tp5&n...

thinkphp虚拟主机部署,Laravel虚拟主机部署

thinkphp虚拟主机部署,Laravel虚拟主机部署

适用于虚拟主机无法设置public目录为网站目录的虚拟主机(1).根目录创建index.php<?php //设置网站目录 $root_path = __DIR__ . DIRECTORY_SEPARATOR . 'publ...

 php连接sqlserver,php连接sql server数据库,php查询sqlserver数据库,php用sqlserver数据库

php连接sqlserver,php连接sql server数据库,php查询sqlserver数据库,php用sqlserver数据库

sqlsrv扩展是php操作SQL Server的驱动下载地址:http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx下载完成后打开解压到指定目录,找到对应php版本的扩展,记得下载nts版本的。下载完扩展后,然后复制指定的dll文件到对应ph...