php分块传输,php – 如何在Laravel中使用分块传输编码?

美好的一天.我想知道我是否可以在API响应中使用分块传输编码(进一步的CTE)?我在数据库中有大量数据,我需要在一个请求中将其传输到客户端.我已经阅读了很多关于CTE机制的内容,但不幸的是我找不到如何实现它.

值得一提的是:没有分页.它应该是一个自治系统,它将数据返回给客户端点,而不是网页.

正如我所提到的,数据存储在数据库中.唯一的问题是如何将数据拆分成段(块)并在一个API响应中逐个发送(一个一个).

谢谢.

解决方法:

我想您可能对查询生成器上的块方法感兴趣.

Chunking Results

If you need to work with thousands of database records, consider using

the chunk method. This method retrieves a small chunk of the results

at a time and feeds each chunk into a Closure for processing. This

method is very useful for writing Artisan commands that process

thousands of records. For example, let’s work with the entire users

table in chunks of 100 records at a time:

$response = new \Symfony\Component\HttpFoundation\StreamedResponse(function() {

$handle = fopen('php://output', 'w');

DB::table('users')->orderBy('id')->chunk(100, function ($users) use($handle) {

foreach ($users as $user) {

fputs($handle, json_encode($user));

}

});

fclose($handle);

});

return $response;

分块传输编码

据我所知,如果你返回一个JSON响应,我会知道Laravel does this by default.

更新:

我的解决方案不必要地复杂和复杂.我删除了StreamedResponse,因为确实没有任何需要它.请参阅下面的更新示例

$json_response = collect();

DB::table('users')->orderBy('id')->chunk(100, function ($users) use($json_response) {

foreach ($users as $user) {

$json_response->push($user);

}

});

return $json_response->toJson();

标签:php,http,rest,laravel,http-1-1

来源: https://codeday.me/bug/20190710/1424348.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值