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

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

高老师9个月前 (05-19)PHP217

应用场景:客户调用服务端,服务器端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将html转为pdf,php将html页面导出pdf

php将html转为pdf,php将html页面导出pdf

首先下载wkhtmltox-0.12.4_linux-generic-amd64.tar.xz   (不要下载RPM包,依赖太多,需要x-server支持),并解压,执行测试运行正常tar wkhtmltox-0.12.4_linux-generic-amd64.tar.xzcd...

php 经纬度获取城市,php 经纬度转城市

php 经纬度获取城市,php 经纬度转城市

通过经纬度转换为城市名称,并获得城市的编号,通常在全国类型的商城中比较通用。//经纬度转城市名称(返回城市id,城市名称) //$ak开发密钥,$lat纬度,$lng经度,$type返回数据类型 public function getCityName($ak,$lat,$lng)...

php 地址转换经纬度

php 地址转换经纬度

//$ak开发密钥,$cityname城市名称(支持省县乡详细地址) public  function   getposition($ak,$cityname){ $callback=array('lng'=>0,'l...

php引用变量的完全理解

php引用变量的完全理解

在PHP中,大部分变量类型,如字符串,整型,浮点,数组等都是值类型的,而类和对象是引用类型.和其他语言有点差距.(1).在值类型中我们直接使用&符号表示指向对应变量的内存地址,当前变量和被指向的变量只要有1个的值被修改都会直接影响另外一个变量的值发生变化。(ps:还是非常节省内存的,可以使用...

php异步执行,php后台运行,如何在windows下让php后台运行

php异步执行,php后台运行,如何在windows下让php后台运行

如果想在windows中执行php,并且让php脚本在后台运行,可以用下面的cmd命令start /b php  D:\wwwroot\default\demo1\run.php例如上面的命令意思后台运行run.php,如果想用php编写异步代码: ...

编写php com组件,php调用.net dll,php源码保护

编写php com组件,php调用.net dll,php源码保护

开发com组件可以用c++,vc++,net,我比较熟悉net,演示用dnet(1).创建项目:启动vs2017,新建项目,选择Visual C# ->Windows桌面->类库通用windows(2). 修改Com项目:点击 项目->项目属性,再点击应用程序->程序集信息,...