dongrao1862 2019-05-05 19:18
浏览 261

如何在PHP中打印大字符串

I'm building a web server and i want my php script to transfer large amounts of data. Which method should i use?

I'm talking about over 20 mb sized strings. I tried to echo them but script cannot print more than 5-6 mb after 1-2 minutes. After that I tried to split strings into blocks and print them, still no luck. Compressing didn't work either since the strings are base64 encoded.

As you can see here, i tried to write the data into a file and download it:

$payload = "my large string";
file_put_contents("payload.txt", $payload);
$download_rate = 100;
$file = fopen("payload.txt", "r");
while(!feof($file)) {
    print fread($file, round($download_rate * 1024));
    flush();
    ob_end_clean();
}
fclose($file);
  • 写回答

1条回答 默认 最新

  • doukang5966907 2019-05-05 20:07
    关注

    Transferring of data, and printing of data (you mean output in browser?) are two very different things. For transferal you would use the appropriate headers.

    What I mean is something like this:

    if (ob_get_level()) ob_end_clean(); // switch output buffering off
    
    $path = "payload.txt";
    
    header("Content-Disposition: attachment; filename=\"" . basename($path) . "\"");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " . filesize($path));
    
    readfile($path);
    

    Nothing complex. Note that the file is downloaded (= transferred) and not rendered in the browser. It's the headers that do the trick and the readfile() of course.

    A quote from the readfile() page:

    Note:
    readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().

    There's also a slightly more advanced example there, with more headers.

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探