Break A Large File Into Many Smaller Files With PHP
If your big file is in CSV format, I guess that you need to process it line by line and don't actually need to break it into smaller files. There should be no need to hold 5.000 or more lines in memory at once! To do that, simply use PHP's "low-level" file functions:
$fp = fopen("path/to/file", "r");
while (false !== ($line = fgets($fp))) {
// Process $line, e.g split it into values since it is CSV.
$values = explode(",", $line);
// Do stuff: Run MySQL updates, ...
}
fclose($fp);
If you need random-access, e.g. read a line by line number, you could create a "line index" for your file:
$fp = fopen("path/to/file", "r");
$index = array(0);
while (false !== ($line = fgets($fp))) {
$index[] = ftell($fp); // get the current byte offset
}
Now $index
maps line numbers to byte offsets and you can navigate to a line by using fseek()
:
function get_line($number)
{
global $fp, $index;
$offset = $index[$number];
fseek($fp, $offset);
return fgets($fp);
}
$line10 = get_line(10);
// ... Once you are done:
fclose($fp);
Note that I started line counting at 0, unlike text editors.
How can I split a big XML file into smallers with PHP?
Please take a look at this article PHP XML Parsing
- SAX parsing
- XML Reader XMLReader Pull Parser
will be the best suited for this job
Read the above article try some code with it you will definitely get the answer for this
Related Topics
How to Keep Leading Zeros in PHP Integer
What's the Best and Easiest Way to Populate a Dropdown Based on Another Dropdown
Phpdoc for Variable-Length Arrays of Arguments
How to Set Base Url for All Pages of My Website
Codeigniter Activerecord: Join Backticking
Redirect to New Page W/ Post Data (Php/Zend)
Get the Auto-Generated Id After an Insert
Set Woocommerce Cart Expiration
Printing PHP Script Output to File
Session Share Across Multiple Domains on Same Server
Can Mongodb and Its Drivers Preserve the Ordering of Document Elements
PHP - Find If an Array Contains an Element
Can Not Increase File Upload Size Wamp