情况是这样的:
我有一个 2Gb 的转储文件,名为myDB.sql。它是一个转储文件,可删除现有数据库并创建一个带有视图和触发器的新数据库。所以我有字符串myDB_OLD
分布在许多行代码中。
我想将这些字符串的出现次数更改为myDB_NEW
。
我可以使用 notePad++ 轻松完成此操作。但是记事本打不开2Gb的文件。
我所做的是逐行读取并查找并替换我想要的字符串的 PHP 代码。
这是代码:
$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";
此代码检索文件的每一行更改字符串,连接变量并创建一个新文件。它应该有效,但事实并非如此。我不知道为什么。我正在使用 xdebug 来找出问题所在,但没有运气。
所以我改变了方法。
我没有将每一行保存在变量中,而是直接将其保存在文件中,效果很好。
这是新代码:
$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";
好的,我解决了我的问题,但它引发了一个想法。第一个代码的问题是什么?
我认为问题在于 PHP 变量中存储的信息量,2Gb。
那么,PHP 变量存储值(在本例中为字符串)的大小是否有限制?
如果是的话我该如何检查或更改它?
有 php.ini 变量吗?