每次发生拆分大文件。

下面的代码每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\')

?>
有任何想法吗?     
已邀请:
        如果我理解正确,应该这样做。
$content = file_get_contents($source);
$parts = explode(\'</byebye>\', $content);
$parts = array_map(\'trim\', $parts);
然后将零件写入不同的文件
$dateString = date(\'m-d-y\');
foreach ($parts as $index => $part) {
  file_put_contents(\"{$targetpath}part_{$dateString}{$index}.xml\", $part);
}
但是我假设(不知道您的来源),这将导致无效的xml。您应该使用XML解析器之一(SimpleXML,DOM,..)来处理xml文件。 旁注:您过多地使用ѭ5。     
        如果您担心大小,则可以切换到文件资源,并使用fread或fgets来控制要访问的内存量。
$f = fopen($source, \"r\");
$out = \'\';

while (!feof($f)) 
{
    $line .= fgets($f);

    $arr = explode(\'</byebye>\', $line);
    $out .= $arr[0];

    if (count($arr) == 1)
        continue;  
    else
    {
        // file_put_contents here
        // will need to handle lines with multiple </byebye> entries here, 
        // outputting as necessary

        // replace $out with the final entry of the $arr array onto 
    }

}
您还可以通过打开文件进行输出来节省更多内存,并在解析时将内容通过管道传递给它。遇到条目时,您将关闭文件并打开下一个文件。     

要回复问题请先登录注册