每次分割大文件发生
下面的代码每 10 行分割我的文件,但我希望它每次发生时都分割
</byebye>
。这样,我将获得多个文件,每个文件包含;
<byebye>
*stuff here*
</byebye>
代码:
<?php
/**
*
* Split large files into smaller ones
* @param string $source Source file
* @param string $targetpath Target directory for saving files
* @param int $lines Number of lines to split
* @return void
*/
function split_file($source, $targetpath='files/', $lines=10){
$i=0;
$j=1;
$date = date("m-d-y");
$buffer='';
$handle = @fopen ($source, "r");
while (!feof ($handle)) {
$buffer .= @fgets($handle, 4096);
$i++;
if ($i >= $lines) {
$fname = $targetpath.".part_".$date.$j.".xml";
if (!$fhandle = @fopen($fname, 'w')) {
echo "Cannot open file ($fname)";
exit;
}
if (!@fwrite($fhandle, $buffer)) {
echo "Cannot write to file ($fname)";
exit;
}
fclose($fhandle);
$j++;
$buffer='';
$i=0;
$line+=10; // add 10 to $lines after each iteration. Modify this line as required
}
}
fclose ($handle);
}
split_file('testxml.xml')
?>
有什么想法吗?
Below code splits my file every 10 lines, but I want it to split everytime
</byebye>
occurs. That way, I will get multiple files each containing;
<byebye>
*stuff here*
</byebye>
Code:
<?php
/**
*
* Split large files into smaller ones
* @param string $source Source file
* @param string $targetpath Target directory for saving files
* @param int $lines Number of lines to split
* @return void
*/
function split_file($source, $targetpath='files/', $lines=10){
$i=0;
$j=1;
$date = date("m-d-y");
$buffer='';
$handle = @fopen ($source, "r");
while (!feof ($handle)) {
$buffer .= @fgets($handle, 4096);
$i++;
if ($i >= $lines) {
$fname = $targetpath.".part_".$date.$j.".xml";
if (!$fhandle = @fopen($fname, 'w')) {
echo "Cannot open file ($fname)";
exit;
}
if (!@fwrite($fhandle, $buffer)) {
echo "Cannot write to file ($fname)";
exit;
}
fclose($fhandle);
$j++;
$buffer='';
$i=0;
$line+=10; // add 10 to $lines after each iteration. Modify this line as required
}
}
fclose ($handle);
}
split_file('testxml.xml')
?>
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确的话,这应该可以。
然后只需将各个部分写入不同的文件,
但我假设(不知道您的来源),这将导致无效 xml。您应该使用 XML 解析器(SimpleXML、DOM、..)之一来处理 xml 文件。
旁注:您使用
@
太多了。If I understand you right, this should do it.
Then just write the parts to the different files
But I assume (without knowing your source), that this will result in invalid xml. You should use one of the XML-Parser (SimpleXML, DOM, ..) to handle xml-files.
Sidenote: You use
@
much much too much.如果您担心大小,可以切换到文件资源并使用 fread 或 fgets 来控制所使用的内存量。
您还可以通过打开文件进行输出来节省更多内存,并在解析时将内容通过管道传递给该文件。当您遇到一个条目时,您将关闭该文件并打开下一个条目。
If you are worried about sizes you can switch to a file resource and use fread or fgets to control the amount of memory you are hitting.
You can also save more memory by opening up the file for output, and as you parse, pipe the contents to it. When you encounter a entry you would close the file and open the next one.