Php 从旧文件创建新文件
我有上面的代码,假设它能够打开一个名为Php 从旧文件创建新文件,php,Php,我有上面的代码,假设它能够打开一个名为“$file”的原始文件并创建一个新文件,然后关闭它,但是它不会创建,当我运行它时,我会收到以下警告错误: while (($line = fgets($handle)) !== false) { //look for the first payor block if(strpos($line, 'N1*PR*') !== false || $block_start) { $header_end = true; $block_start = true;
“$file”
的原始文件并创建一个新文件,然后关闭它,但是它不会创建,当我运行它时,我会收到以下警告错误:
while (($line = fgets($handle)) !== false) {
//look for the first payor block
if(strpos($line, 'N1*PR*') !== false || $block_start) {
$header_end = true; $block_start = true;
//see if the block finished
if(strpos($line, 'CAS*CO*45*20.43**253*1.27~') !== false) {
$block_start = false;
$payor_blocks[$count] .= $line;
$count++;
}
$payor_blocks[$count] .= $line;
} else {
//append to the header
if($header_end) {
$footer .= $line."\n";
} else {
$header .= $line."\n";
}
}
}
//get payor blocks and create a file foreach payor
$new_files = array();
foreach($payor_blocks as $block) {
$filename = $file . "_" . $count;
$count++;
$new_files[] = array(
'name' => $filename,
'content' => $header."\n".$block."\n".$footer
);
//loop through new files and create them
foreach($new_files as $new_file) {
$myfile = fopen($file, "x");
fwrite($myfile, $new_file['content']);
//close the file
fclose($myfile);
任何帮助都将不胜感激
我有一个文件名为:362931550.1a
我编写了一段代码,在某些区域将它们拆分(发布时间相当长),当我运行脚本时,我在浏览器上看到它,但它不会在文件夹中创建2个新文件。您的文件打开模式不正确 发件人: “x”创建并仅用于书写;将文件指针放在文件的开头。如果文件已经存在,则fopen()调用将失败,返回FALSE并生成级别为E_警告[…]的错误 您可能应该使用“w”模式: “w”仅限书写;将文件指针放在文件的开头,并将文件截断为零长度。如果文件不存在,请尝试创建它
脚本无法使用
fopen()
函数打开流并返回布尔值。函数fwrite()
将成为布尔值,但需要一个资源
原因是您仅在流中使用x修改器创建文件
创建并仅开放用于写作;将文件指针放在文件的开头。如果文件已经存在,则fopen()调用将失败,返回FALSE并生成级别为E_警告的错误。如果文件不存在,请尝试创建它
您可以在PHP手册中看到有关流模式()的更多信息
要阻止此消息,请检查该值是否为false
Warning: fopen(362931550.1a): failed to open stream:
File exists in /script2.php on line 90 Warning:
fwrite() expects parameter 1 to be resource,
boolean given in /script2.php on line 94 Warning:
fclose() expects parameter 1 to be resource, boolean
given in /script2.php on line 96
阅读使用
x
mode-如果文件已经存在,那么fopen()调用将失败,返回FALSE并生成一个E_级警告错误。
我试图输入w,但没有得到我想要的输出。你知道我还可以输入什么吗@u_Mulder我们不知道您想要什么输出和得到什么,所以请编辑您的问题并澄清。完成检查@u_Mulder没有更多上下文,我们无法确定发生了什么,但您正在打开$file
进行编写,而不是$new_file
。除非你在循环中改变$file
的值,否则你只是在一遍又一遍地打开和写入同一个文件…我可以用什么来代替x来提供我想要的输出?我尝试过它只放置一个文件而不是旧文件,它不会创建两个新文件。你的示例中没有创建两个文件的代码。请澄清您的问题。我发布了与之相关的代码,正如我所提到的,我的代码非常长,如果我全部发布,它将非常模糊。
$stream = fopen("file.txt", "x");
if($stream === false) {
echo "Error while open stream";
}
//here your code