将PHP脚本更改为从阵列中输出每个2000行的打印文件

时间:2012-03-24 08:42:36

标签: php json foreach

我需要一些帮助,让我按照自己的方式工作。

我正在尝试将easylist.txt转换为特定的Json格式并导入到我的Untangle防火墙。

Bellow是我正在运行以转换它的PHP脚本。 问题是导入期间有大约2000行的限制。 所以我需要它为每个2000行创建一个导出文件。并根据需要执行尽可能多的文件。

这个问题的任何帮助都是假定的。

感谢WebFooL

<?php
$Content = "./easylist.txt"; 
$lines = file($Content); 
$vJsonFileName = "AD-Blocker". ".json"; 
$badcharacters = array("#",'"', "'", "[", "]", "\n", "\t"); 
header("Content-type: application/json"); 
header("Content-Disposition: attachment; filename=$vJsonFileName");
header('Cache-Control: public');
echo "["; 
foreach($lines as $str){ 
$cleanstr = str_replace($badcharacters, "", $str);
echo '{"enabled":true,"string":"'.$cleanstr.'","javaClass":"com.untangle.uvm.node.GenericRule"},'; 
}
echo "]"; 
?>

2 个答案:

答案 0 :(得分:0)

假设您可以随意拆分输入数据(即条目不跨越多行并且每行都是“原子”),那么您只需提取所需的行数

$Content = "./easylist.txt"; 
$lines = file($Content); 
$linesSplit = array_chunk( $lines, 2000 );
顺便说一句,你真的需要删除“坏人物”吗?您是否使用json_encode进行了调查?

答案 1 :(得分:0)

您无法下载多个文件,因此以下内容将创建多个文件。 这里有关于压缩文件的帖子:How to [recursively] Zip a directory in PHP?

<?php
$Content = "./easylist.txt"; 
$lines = file($Content); 
$vJsonFileName = "AD-Blocker.zip"; 
$badcharacters = array("#",'"', "'", "[", "]", "\n", "\t"); 
$f = 1;
foreach($lines as $str)
{
    $c++;
    if($c==2000)
    {
        $f++;
    }
    $cleanstr = str_replace($badcharacters, "", $str);
    $json[$f] = '{"enabled":true,"string":"'.$cleanstr.'","javaClass":"com.untangle.uvm.node.GenericRule"},'; 
}

foreach($json as $f => $arr)
{
    file_put_contents('file'.$f,'['.implode('',$arr).']');
}


//zip up all the files here to $vJsonFileName


header("Content-type: application/json"); 
header("Content-Disposition: attachment; filename=$vJsonFileName");
header('Cache-Control: public');
?>
相关问题