dthjnc306679 2016-06-03 11:44
浏览 28
已采纳

PHP处理大文件[重复]

This question already has an answer here:

I've got a 1.5gig big file where I want to do some replacements.

But my apache runs out of memory. Is there a possibility to this job line by line?

<?php

$myfile = fopen("./m.sql", "r") or die("Unable to open file!");

$dateiinhalt = file_get_contents("./m.sql");


$search = array("ä",
    "Ä",
    "ö",
    "Ö",
    "ü",
    "Ü",
    "€",
    "§",
    "ß",
    "latin1_general_ci",
    "CHARSET=latin1",
    "‚",
    "„",
    "‘",
    "’",
    "“",
    "â€",
    "©",
    "®");

$replace = array("ä",
    "Ä",
    "ö",
    "Ö",
    "ü",
    "Ü",
    "€",
    "§",
    "ß",
    "utf8_general_ci",
    "CHARSET=utf8",
    "‚",
    "„",
    "‘",
    "’",
    "“",
    "”",
    "©",
    "®");


$content = str_replace($search, $replace, $dateiinhalt);
file_put_contents("./m.sql", $content);

echo "done";

thanks at all

Updated Code:

$reading = fopen('m.sql', 'r');
$writing = fopen('m.tmp', 'w');

$replaced = false;



$search = array("ä",
    "Ä",
    "ö",
    "Ö",
    "ü",
    "Ü",
    "€",
    "§",
    "ß",
    "latin1_general_ci",
    "CHARSET=latin1",
    "‚",
    "„",
    "‘",
    "’",
    "“",
    "â€",
    "©",
    "®");

$replace = array("ä",
    "Ä",
    "ö",
    "Ö",
    "ü",
    "Ü",
    "€",
    "§",
    "ß",
    "utf8_general_ci",
    "CHARSET=utf8",
    "‚",
    "„",
    "‘",
    "’",
    "“",
    "”",
    "©",
    "®");

if ($reading) {
    // read one line or 4096 bytes, whichever comes first
    while (($dateiinhalt = fgets($reading, 4096)) !== false) {
        // replace in that and write to output file
        fwrite($writing, str_replace($search, $replace, $dateiinhalt));
    }
    if (!feof($reading)) { // fgets() failed, but not at end of file
        echo "Error: unexpected fgets() fail
";
    }
    fclose($reading);
    fclose($writing);
}

echo "done";

</div>
  • 写回答

3条回答 默认 最新

  • douyu2817 2016-06-03 11:51
    关注

    Yes. Its not hard. You seem to have already started - you should not open a file before running file_get_contents() on it (unless you explicitly want to lock it).

    $search=Array(...
    $replace=Array(...
    $myfile = fopen("./m.sql", "r");
    $output = fopen("./output.sql", "w");
    while ($line=fgets($myfile)) {
       fputs($output, str_replace($search, $replace, $line));
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?