Creating new files from an old one - php

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);
I have the code above, it's suppose to be able to open an original file called "$file" and create a new file then close it, However its not creating and when I run it, i get this warning error:
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
Any help is kindly appreciated.
I have one file named: 362931550.1a
I did a code that splits them at certain areas, (its pretty long to post), when i run the script I see it on my browser but it doesn't create 2 new files in the folder.

Your file open mode is incorrect.
From php.net documentation:
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING [...]
You should probably use 'w' mode:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

The script failed to open a stream with the fopen() function and return a boolean. The function fwrite() become the boolean value but need a resource.
The reason is that you only create files with the x-modifier in the stream.
Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it.
You see in the PHP manual more informations about the stream-modes (PHP manual).
To prevent this message check if the value isn't false.
$stream = fopen("file.txt", "x");
if($stream === false) {
echo "Error while open stream";
}
//here your code

Related

Read a txt file in Storage

I have this file that is already stored in Storage. It's a txt file that contains data lines recorded as show picture below. I get this file using the Storage facade like
$file = Storage::get('public/' . $model->path_to_file);
dd($file); // <- output the picture below
Now I need read each line on this file, but can't figure it out how this must be done. Someone can help me?
I try this code but give me an exception:
$fp = fopen(Storage::path('public/' . $file_path->path_to_file), "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
echo $line;
}
fclose($fp);
... 580583507 05-08-2021 15:20:09 05-08-2021 15:20:47 Luca RemoteControl {260f5a65-35a4-4b57-bd21-b378f0ab7b82}): failed to open stream: Invalid argument
How this must be solve?
You can use the comand feof (find end of file), so you can do anything you want to inside the loop.
$fp = fopen(Storage::path('public/' . $file_path->path_to_file), "r");
while(!feof($fp)){
$line = fgets($fp);
print_r($line."\n");
}
fclose($fp);

Copy a file's text to another file PHP

I want to copy the content from (Bazamod.txt) to (compile.txt) but I get this error:
Warning: fopen(LicenteSi/Test/compile.txt): failed to open stream: No
such file or directory in
/storage/ssd3/361/16261361/public_html/createL.php on line 137
Warning: fwrite() expects parameter 1 to be resource, boolean given in
/storage/ssd3/361/16261361/public_html/createL.php on line 141
Function create_compile_mod($Licence_Name, $Path){
$FilePath = "$Path/compile.txt";
$myFile = fopen($FilePath, "r+");
copy("bazamod/Bazamod.txt", $FilePath);
fwrite($myFile, $FilePath);
}
Thank you!
If you what you need to do is just to copy the contents of Bazamod.txt to compile.txt, by providing a path to compile.txt as argument, then the following function will do the trick:
<?php
function create_compile_mod($Path)
{
$fileContents = file_get_contents("bazamod/Bazamod.txt");
$fileHandle = fopen($Path . "/compile.txt", "r+");
fputs($fileHandle, $fileContents);
fclose($fileHandle);
}
?>
I have not included your $Licence_Name argument as it does not seem to be used, but you can adapt the above code to fit your needs.
Keep in mind that the above code will copy the entire contents of Bazamod.txt and replace the existing contents of compile.txt. If you would just like to append new text, use the "a" access mode instead of the specified "r+", and the text will automatically be added at the bottom of the document.
If you need to add at a specific line, you could go for:
<?php
function create_compile_mod($Path, $lineIndex)
{
$oldContents = file_get_contents("bazamod/Bazamod.txt");
$compileArray = file($Path . "compile.txt");
array_splice($compileArray, $lineIndex, 0, $oldContents);
$newContent = implode(PHP_EOL, $compileArray);
$compileFh = fopen($Path . "compile.txt", "r+");
fputs($compileFh, $newContent);
}
?>
Specify your $lineIndex to be the line number at which you want you content to be put (starting from line 0), and call your function like create_compile_mod("./", 4).

Search file for word and delete line

This is a second request on the same subject. I wasn't clear
I needed the line to be deleted.
I searched here and found part of a script that is suppose search for
a word and delete the line. There seems to be a slight error with what
I'm trying to do.
I have an option list in a pull down. I would like for it to
remove the line selected. The file choice.php that is called
from the pull down page seems to be released when the php below
is called called because there is no access denied, or violation
errors.
These are the errors I'm getting after adding the 3 last lines I
was told I need.
fopen() expects at least 2 parameters, 1 given
implode(): Invalid arguments passed
fwrite() expects parameter 1 to be resource, boolean given
fclose() expects parameter 1 to be resource, boolean given
Thanks in advance
<?php
// Separate choice.php has the following pull down
// Select item to delete from list
// <option value="item1.php">Item 1</option>
// <option value="item2.php">Item 2</option>
// ...... many items.
$workitem = $_POST["itemtodelete"];
$file = file("option.list.php");
foreach( $file as $key=>$line ) {
if( false !== strpos($line, $workitem) ) {
unset ($file[$key]);
}
}
// Removed "\n"
$file = implode("", $file);
// Told to add this.
$fp = fopen ("option.list.php");
fwrite($fp,implode("",$file);
fclose ($fp);
?>
fopen requires a $mode as the second parameter, so that fails and everything that needs $fp.
Just use file_put_contents. It will even implode the array for you:
$workitem = $_POST["itemtodelete"];
$file = file("option.list.php");
foreach( $file as $key=>$line ) {
if( false !== strpos($line, $workitem) ) {
unset ($file[$key]);
}
}
file_put_contents('option.list.php', $file);
Ok. You are missing some closing parenthesis, as well as other things.
$replaceItem = $_POST['itemtodelete']; // You should filter this data
$newContents = "";
$path = PATH_TO_FILE; // This could be hard coded, but not recommended
$filename = "option.list.php";
// Check to see if the file exists
if ( file_exists($path."/".$filename) ) {
// Wrap our IO stuff so we catch any exceptions
try {
// Open the file for reading
$fp = fopen($path."/".$filename, "r");
if ($fp) {
// Loop line-by-line through the file
while($line = fgets($fp, 4096) !== false) {
// Only add the line if it doesn't contain $replaceItem
// This is case insensitive. I.E. 'item' == 'ITEM'
// For case sensitive, use strstr()
if ( stristr($line, $replaceItem) == false ) {
$newContents .= $line;
}
}
}
// Close our file
fclose($fp);
// Replace the contents of the file with the new contents
file_put_contents($path."/".$filename, $newContents);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
Edit: Try this. I modified it somewhat.

Push file to array in loop

EDIT after all the answers, i updated the function, and it works
I read out a importfolder. In this folder are many different files available.
Step: I read the folder and add the files to a array
Step: I open every file and try to import
When i cant import a file, then this happens, when another file in this row have to be imported first.
Example: If I open a file "message to a address", this could not be imported, when the address are not added into the database. But in some other file of this filelist is the "create address"-file. When this is created, then it is good, when the "message to a address" will be added to the filelistarray on the end.
My Code give me an offset problem:
function importData( $path, $db, $mail )
{
//Get available Importfiles
$filelist = getFilelist( $path );
for ($i = 0; $i < count($filelist); $i++)
{
$filename = $path . "/" . $filelist[$i];
$file = fopen( $filename,"r" );
while(!feof( $file )) {
$items = explode( ";", fgets( $file ) );
//Get messagetyp
if( strtolower(trim($items[0])) == "nachrichtentyp" )
{
$messagetyp = $items[1];
break;
}
}
fclose($file);
if ( $messagetyp )
{
$f = "import" . $messagetyp;
if( !$f($filename, $db, $mail) )
{
array_push($filelist, $filelist[$i]);
}
}
}
}
This my error, when I push the element to the the filelist-array
PHP Warning: feof() expects parameter 1 to be resource, boolean given in /var/www/symfony/importscript/import.php on line 37
PHP Warning: fgets() expects parameter 1 to be resource, boolean given in /var/www/symfony/importscript/import.php on line 38
According to your errors, problem lies not in array_push but in fopen():
$file = fopen( $filename,"r" );
If php fails to open that file, variable $file will be set to false and because of that feof() and fgets() will give you errors.
You definitely should check if fopen returns another value than FALSE, maybe one of the files does not exist or you are restricted.

feof(): 3 is not a valid stream resource in

after i have installed windows 8 on my desktop and reinstalled aptana and xampp, i somehow can't use !feof($handle). i want to get the symbols of nasdaq stored in my $symb arra.here is an example and my error:
$symb = array();
$url = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
$handle = fopen("$url","r");
while( !feof($handle) ){
$line = fgetcsv($handle, 1024);
if($line!="Symbol" && isset($line[0]) && $line[0] != null ){
$symb[] = trim($line[0]);
}
fclose($handle);
}
And my Errors :
Warning: feof(): 3 is not a valid stream resource in C:\xampp\htdocs\demos\screener\candleScreener.php on line 61
Warning: fgetcsv(): 3 is not a valid stream resource in C:\xampp\htdocs\demos\screener\candleScreener.php on line 62
Warning: fclose(): 3 is not a valid stream resource in C:\xampp\htdocs\demos\screener\candleScreener.php on line 66
.......
Is there a setting i have to change on the php.ini file or what could it be ?
thanks.
.....
$url = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
$handle = fopen("$url","r");
$txt = fread( $handle, 8 );
print_r($txt);
.....
prints out :
"Symbol"
so my fopen() is fine ....
The reinstallation and the fopen() are red herrings. You're closing the file handle inside the while loop, before the file has been read.
while( !feof($handle) ){
$line = fgetcsv($handle, 1024);
if($line!="Symbol" && isset($line[0]) && $line[0] != null ){
$symb[] = trim($line[0]);
}
// fclose($handle); // Move this outside the while loop
}
fclose($handle); // Moved this outside the while loop
I had the same problem in my code. I had an extra file close function in the code. In other words I was trying to write to the file for a second time and it was not open for use. I had this coded in the top of my program:
$newFile = $local_directory . $tenant.'-'.$namespace.'_Stats.xml';
$newDoc = fopen($newFile, "w");
fwrite($newDoc, $urlStats);
fwrite($newDoc, $response);
fclose($newDoc);
Then later I had:
fwrite($newDoc, $response);
fclose($newDoc);
Check to make sure the file is open before you write more content.

Categories