处理一个长度为 3000 万个字符的字符串

Manipulate a string that is 30 million characters long(处理一个长度为 3000 万个字符的字符串)
本文介绍了处理一个长度为 3000 万个字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在从另一台服务器下载一个 CSV 文件作为来自供应商的数据源.

I am downloading a CSV file from another server as a data feed from a vendor.

我正在使用 curl 来获取文件的内容并将其保存到一个名为 $contents 的变量中.

I am using curl to get the contents of the file and saving that into a variable called $contents.

我可以很好地到达那部分,但是我尝试通过 进行爆炸以获取行数组,但它失败并显示 'out of内存错误.

I can get to that part just fine, but I tried exploding by and to get an array of lines but it fails with an 'out of memory' error.

echo strlen($contents) 大约有 3050 万个字符.

I echo strlen($contents) and it's about 30.5 million chars.

我需要操作这些值并将它们插入到数据库中.我需要做什么来避免内存分配错误?

I need to manipulate the values and insert them into a database. What do I need to do to avoid memory allocation errors?

推荐答案

PHP 因内存不足而窒息.不要让 curl 用文件内容填充 PHP 变量,而是使用

PHP is choking because it's running out memory. Instead of having curl populate a PHP variable with the contents of the file, use the

CURLOPT_FILE

改为将文件保存到磁盘的选项.

option to save the file to disk instead.

//pseudo, untested code to give you the idea

$fp = fopen('path/to/save/file', 'w');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec ($ch);
curl_close ($ch);
fclose($fp);

然后,一旦文件被保存,而不是使用 filefile_get_contents 函数(这会将整个文件加载到内存中,再次杀死 PHP),使用 fopen 和 fgets 读取文件一行一次.

Then, once the file is saved, instead of using the file or file_get_contents functions (which would load the entire file into memory, killing PHP again), use fopen and fgets to read the file one line at a time.

这篇关于处理一个长度为 3000 万个字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)