PHP在大型CSV中查找和替换时遇到问题
我正在编写一个PHP脚本,这样我就可以在一个大的CSV文件中进行查找和替换。我写了这个剧本:PHP在大型CSV中查找和替换时遇到问题,php,csv,Php,Csv,我正在编写一个PHP脚本,这样我就可以在一个大的CSV文件中进行查找和替换。我写了这个剧本: // FIND AND REPLACE $sourcePath = 'custom.csv'; $tempPath = $sourcePath . 'temp'; $source = fopen($sourcePath, 'r'); $target = fopen($tempPath, 'w'); while(!feof($source)) { $line = preg_replace
// FIND AND REPLACE
$sourcePath = 'custom.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
while(!feof($source)) {
$line = preg_replace ("village", "village/",fgets($source));
fwrite($target, $line);
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
但是我得到了这些错误
Warning: feof() expects parameter 1 to be resource, boolean given
Warning: fgets() expects parameter 1 to be resource, boolean given
Warning: preg_replace(): Delimiter must not be alphanumeric or backslash
您没有检查fopen是否实际返回文件指针资源或错误结果。它很可能返回false并发出警告,表示提供了布尔值 此外,您还可以使用:
$line = str_replace("village", "village/", fgets($source));
$source=fopen($sourcePath,'r')代码>没有返回您认为的内容
它可能返回false,这通常发生在PHP无法在您提供的路径上找到文件时。如果确定该文件存在,则应确认执行脚本的用户具有读取该文件的适当权限
第二个问题是关于未使用分隔符导致的preg\u replace()
。在第一个论点中,它们是必要的
$line = preg_replace ("/village/", "village/",fgets($source));
但是,这种简单的替换不需要正则表达式。您应该改为使用str_replace()
,脚本应该运行得更快
您的代码应该如下所示:
<?php
$sourcePath = 'custom.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
if($source){
while(!feof($source)) {
$line = str_replace("Village\\", "Village",fgets($source));
fwrite($target, $line);
}
} else {
echo "$sourcePath not found, or using the wrong permissions.";
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
?>
如何:文件内容(“custom.csvtemp”、str\u替换(“village”、“village/”、文件内容(“custom.csv”))代码>?!文件太大,无法加载到内存中,因此我必须使用fgets一点一点地加载文件。使用一些命令行(os)工具可能会更快。我认为我使用exec命令来使用iconv,但如果有,是否有一个用于替换的工具会更好。你知道有没有?嗨,我需要用“Villege”来代替“Villege”。执行此$line=str_replace(“Villege\”、“Villege”、fgets($source))的树ID;但是出现错误“Parse error:syntax error,意外的'Villege'(T_STRING)”您在第一个参数中包含了一个反斜杠,它将转义应该包含该参数的双引号。您需要在第一个反斜杠之前再添加一个反斜杠,让PHP知道它是字符串的一部分(别担心,您仍然只会匹配1个反斜杠)。此外,如果您在搜索行中查找Village\\,Village\\应该是第二个参数。$line=str_replace(“Villege”,“Villege\\”,fgets($source))
有关str_replace()的更多信息:有关反斜杠问题的更多信息:我查看了手册混合str_replace(mixed$search,mixed$replace,mixed$subject[,int&$count])
我想我的命令应该是,因为手册上说第一个变量是search,我搜索的是“Villege\”,而不是$line=str_replace(“Villege\”,“Villege”,fgets($source))
我更改了代码以使其更简单。但是字符串现在根本没有被替换。$sourcePath='estmentexport.csv';$targetPath='estmentexporttarget.csv';$source=fopen($sourcePath,'r');$target=fopen($targetPath,'w');而(!feof($source)){$line=str替换(“Villege\\”,“Villege”,fgets($source));fwrite($target,$line);}fclose($source);fclose($target);