This is so: I have a 2Gb dump file named myDB.sql . This is a dump file that deletes an existing database and creates a new one, with views and triggers. Therefore, I have a line myDB_OLD spread for many lines of code. I would like to change these string occurrences to myDB_NEW . I could do this easily using notePad ++. But notepad does not open a 2Gb file. What I did is PHP code that reads line by line and finds and replaces the line I want.
This is the code:
$myfile2 = fopen("myDB.sql", "r") or die("Unable to open file!");//Reads the file while (!feof($myfile2)) {//Pass trough each line $str=fgets($myfile2);//Store the line inside a variable if (preg_match("/myDB_OLD/",$str)) {//If the string I want to change exists - replace it and conacatenate $newStr .= str_replace("myDB_OLD","myDB_NEW",$str); } else {//If not concatenate it $newStr .=$str; } }//End of while fclose($myfile2); //Save the newStr in a new file named $myfile = fopen("newDB.sql", "w") or die("Unable to open file!"); fwrite($myfile, $newStr); echo "finished";
This code extracts each line of the file, changes the line, concatenates in the variable, and creates a new file. It should work, but it is not. I do not know why. I use xdebug to find out what the problem is, but no luck.
Therefore, I am changing the approach. Instead of saving each line in a variable, I save it directly to a file and this works well.
This is the new code:
$myfile = fopen("newDB.sql", "w") or die("Unable to open file!");//Creates a new file "newDB.sql" $myfile2 = fopen("myDB.sql", "r") or die("Unable to open file!");//Reads the file while (!feof($myfile2)) {//Pass trough each line $str=fgets($myfile2);//Store the line inside a variable if (preg_match("/myDB/",$str)) {//If the string I want to change exists - replace it . (Do not concatenate) $strRep=str_replace("myDB","myDB_NEW",$str); } else { $strRep =$str; } fwrite($myfile, $strRep);// Add the new line to the file "newDB.sql" }//End of while fclose($myfile); fclose($myfile2); echo "finished";
Well, I solved my problem, but it causes a thought. What is the problem of the first code? I think the problem is the amount of information that needs to be stored in the PHP variable, 2Gb. So, is there a size limit on the size of a PHP variable to hold a value, in this case a string? If so, how can I check or change it? Any php.ini variable?