php fgets, fwrite and newline - php
Using php fgets function , I am reading from one file, file "A" which is in a particular format and I am writing to another file, file "B" in a particular format using fwrite.
However, no matter what new lines or line breakers I put, some characters keep being misplaced.
Below is the format I wish to see in the new file, file B:
ICCID,IMSI,KI,ESN,PIN1,PUK1,PIN2,PUK2,IMSI2,KI2,ACC_NBR,NAI_USERNAME,NAI_PASS
8926003010422000616F,,,645030142200061,2064,16002217,4029,34594354,,,,,
8926003010422000624F,,,645030142200062,8678,91445678,5351,06417774,,,,,
8926003010422000632F,,,645030142200063,0356,51052167,6976,27210792,,,,,
8926003010422000640F,,,645030142200064,5504,38104570,4917,61385706,,,,,
8926003010422000657F,,,645030142200065,7158,23625228,2726,13487033,,,,,
8926003010422000665F,,,645030142200066,3922,52488665,6014,33705660,,,,,
BUT below is exactly what I am getting:
ICCID,IMSI,KI,ESN,PIN1,PUK1,PIN2,PUK2,IMSI2,KI2,ACC_NBR,NAI_USERNAME,NAI_PASS
8926003010422000608F,,,645030142200060,3741,26564507,7283,13507659
,,,,,8926003010422000616F,,,645030142200061,2064,16002217,4029,34594354
,,,,,8926003010422000624F,,,645030142200062,8678,91445678,5351,06417774
,,,,,8926003010422000632F,,,645030142200063,0356,51052167,6976,27210792
,,,,,8926003010422000640F,,,645030142200064,5504,38104570,4917,61385706
,,,,,8926003010422000657F,,,645030142200065,7158,23625228,2726,13487033
,,,,,,,,,,,,,,,,,
you will notice the characters ,,,,, get put at the start of a line rather than the end where I want them to be. Notice also the last line gets to be ,,,,,,,,,,,,,,,,,. Not needed at all.
Below is the code that reads and writes. Needing someone to help me sort out this.
$headStockin= "ICCID,IMSI,KI,ESN,PIN1,PUK1,PIN2,PUK2,IMSI2,KI2,ACC_NBR,NAI_USERNAME,NAI_PASSWORD"."\r\n";
$file = fopen($inputFile, "r"); // reading input file
$myStockinfile = fopen($inputFile."_StockIn.txt", "wb") or die("Unable to create/open a file!");
fwrite($myStockinfile, $headStockin);
$thr=",,,";
$one=",";
$fiv=",,,,,";
$lineNo = 0;
$startLine = 21;
while(!feof($file)){
$lineNo++;
$line = fgets($file);
if ($lineNo >= $startLine) {
$result = explode(" ", $line);
$in= $result[2].$thr.$result[1].$one.$result[3].$one.$result[5].$one.$result[4].$one.$result[6].$fiv;
echo $in; //to see output on html
fwrite($myStockinfile,$in);
}
}
fclose($file);
fclose($myStockinfile);
}
INPUT FILE BELOW
*
********************************************************************************
* HEADER DESCRIPTION
********************************************************************************
*
Quantity: 5000
*
********************************************************************************
* INPUT VARIABLES
********************************************************************************
*
var_in_list:
IMSI: 645030142200060
Ser_Nb: 8926003010422000608F
*
********************************************************************************
* OUTPUT VARIABLES
********************************************************************************
*
var_out:MSISDN/IMSI/ICCID/PIN1/PIN2/PUK1/PUK2
+260950605404 645030142200060 8926003010422000608F 3741 7283 26564507 13507659
+260950605411 645030142200061 8926003010422000616F 2064 4029 16002217 34594354
+260950605412 645030142200062 8926003010422000624F 8678 5351 91445678 06417774
+260950605416 645030142200063 8926003010422000632F 0356 6976 51052167 27210792
+260950605418 645030142200064 8926003010422000640F 5504 4917 38104570 61385706
+260950605421 645030142200065 8926003010422000657F 7158 2726 23625228 13487033
The misplaced commas are because fgets() returns a string that includes the newline at the end. So $fesult[6] has a newline at the end, so $fiv gets put onto the next line. The solution is to trim the input before exploding, and then write a newline in your output.
The extra line is because you're testing for EOF before reading the line. feof() isn't detected until after you read the end of the file.
So change your loop to:
while ($line = fgets($file)) {
$lineNo++;
if ($lineNo < 21) { // Skip first 20 lines
continue;
}
$line = rtrim($line);
$result = explode(" ", $line);
$in= $result[2].$thr.$result[1].$one.$result[3].$one.$result[5].$one.$result[4].$one.$result[6].$fiv.PHP_EOL;
echo $in;
fwrite($myStockinfile, $in);
}
Related
How to write the whole array of information into a file?
The script outputs a list and must write the entire list to a file. Why does the script write only the last line to the .txt file, and not the entire list? How do I fix a script to write the entire list to a .txt file? $dir = "./radio/radio_stantion/"; $name = scandir($dir); for($i=2; $i<=(sizeof($name)-1); $i++) { $fopen=file( $dir.$name[$i] ); $line = $fopen[3]; $url = $fopen[2]; $radio_name = explode(") ", $line); $radio_url = explode("//", $url); $link = $radio_url[1]; $http = explode(":", $link); $fff = $http[1]; $port = explode("/", $fff); $zzz = $radio_name[1]; $finalname = preg_replace ("/[^a-zа-я\s]/si","",$zzz); $sss = $finalname."-".$http[0]."-".$port[0]; -------------------------- A list is displayed: FRESH FM IBADAN s4.voscast.com 8442 Bestfriend FM 178.32.62.172 8217 COOLfahrenheit 111.223.51.7 8005 RThess 37.59.32.115 6156 SmoothJazzcom 149.56.155.209 80 -------------------------- $f = fopen("../top_100/radio_top_100_v2.txt", "w"); fwrite($f, $sss); fclose($f); }
I barely understand whats going on there but the problem is that you are opening the file in write mode on each loop iteration. Using fopen with w mode clears the file and writes to it: '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. You should fopen the file before the loop. fwrite on each iteration. and fclose after the loop. $f = fopen("../top_100/radio_top_100_v2.txt", "w"); for($i=2; $i<=(sizeof($name)-1); $i++) { ... fwrite($f, $sss); ... } fclose($f);
I think you are overwriting the previous writes in every iteration. Try writing everything to a string variable first(and append a \n to each line), then write the string contents to the file one time. If you are dealing with a lot of data, then it would make sense to use fwrite every iteration, so not to consume too much memory. File IO is expensive, so only opening the file once, and writing once, should improve performance as well.
How to read a certain line from a string via PHP? [duplicate]
I am working on reading a file in php. I need to read specific lines of the file. I used this code: fseek($file_handle,$start); while (!feof($file_handle)) { ///Get and read the line of the file pointed at. $line = fgets($file_handle); $lineArray .= $line."LINE_SEPARATOR"; processLine($lineArray, $linecount, $logger, $xmlReply); $counter++; } fclose($file_handle); However I realized that the fseek() takes the number of bytes and not the line number. Does PHP have other function that bases its pointer in line numbers? Or do I have to read the file from the start every time, and have a counter until my desired line number is read? I'm looking for an efficient algorithm, stepping over 500-1000 Kb file to get to the desired line seems inefficient.
Use SplFileObject::seek $file = new SplFileObject('yourfile.txt'); $file->seek(123); // seek to line 124 (0-based)
Does this work for you? $file = "name-of-my-file.txt"; $lines = file( $file ); echo $lines[67]; // echos line 68 (lines numbers start at 0 (replace 68 with whatever)) You would obviously need to check the lines exists before printing though. Any good?
You could do like: $lines = file($filename); //file in to an array echo $lines[1]; //line 2 OR $line = 0; $fh = fopen($myFile, 'r'); while (($buffer = fgets($fh)) !== FALSE) { if ($line == 1) { // $buffer is the second line. break; } $line++; }
You must read from the beginning. But if the file never/rarely changes, you could cache the line offsets somewhere else, perhaps in another file.
Try this,the simplest one $buffer=explode("\n",file_get_contents("filename"));//Split data to array for each "\n" Now the buffer is an array and each array index contain each lines; To get the 5th line echo $buffer[4];
You could use function file($filename) . This function reads data from the file into array.
How to append text to a file a 15 lines above its end
I am trying add HTML to a file using fwrite(). My final goal is to get it to add it 15 lines above the end of the file. Here is what I have so far: <?php $file = fopen("index.html", "r+"); // Seek to the end fseek($file, SEEK_END, 0); // Get and save that position $filesize = ftell($file); // Seek to half the length of the file fseek($file, SEEK_SET, $filesize + 15); // Write your data $main = <<<MAIN //html goes here MAIN; fwrite($file, $main); // Close the file handler fclose($file); ?> This just keeps overwriting the top of the file. Thanks.
The sample code in the question does not operate based on lines, since you're working with file size (unless there is an assumption about definition of lines in the application that is not mentioned in here). If you want to work with lines, then you'd need to search for new line characters (which separates each line with the next). If the target file is not a large file (so we could load the whole file into memory), we could use PHP built-in file() to read all the lines of the file into an array, and then insert the data after the 15th element. something like this: <?php $lines = file($filename); $num_lines = count($lines); if ($num_lines > 15) { array_splice($lines, $num_lines - 15, 0, array($content)); file_put_contents($filename, implode('', $lines)); } else { file_put_contents($filename, PHP_EOL . $content, FILE_APPEND); }
How do I choose a specific line from a file?
I'm trying to make (as immature as this sounds) an application online that prints random insults. I have a list that is 140 lines long, and I would like to print one entire line. There is mt_rand(min,max) but when I use that alongside fgets(file, "line") It doesn't give me the line of the random number, it gives me the character. Any help? I have all the code so far below. <?php $file = fopen("Insults.txt","r"); echo fgets($file, (mt_rand(1, 140))); fclose($file); ?>
Try this, it's easier version of what you want to do: $file = file('Insults.txt'); echo $file[array_rand($file)];
$lines = file("Insults.txt"); echo $lines[array_rand($lines)]; Or within a function: function random_line($filename) { $lines = file($filename) ; return $lines[array_rand($lines)] ; } $insult = random_line("Insults.txt"); echo $insult;
use file() for this. it returns an array with the lines of the file: $lines = file($filename); $line = mt_rand(0, count($lines)); echo $lines[$line];
First: You totally screwed on using fgets() correctly, please refer to the manual about the meaning of the second parameter (it just plainly not what you think it is). Second: the file() solution will work... until the filesize exceeds a certain size and exhaust the complete PHP memory. Keep in mind: file() reads the complete file into an array. You might be better off with reading line-by-line, even if that means you'll have to discard most of the read data. $fp = fopen(...); $line = 129; // read (and ignore) the first 128 lines in the file $i = 1; while ($i < $line) { fgets($fp); $i++; } // at last: this is the line we wanted $theLine = fgets($fp); (not tested!)
PHP to delete lines within text file beginning with 0 or a negative number
Thank you for taking the time to read this and I will appreciate every single response no mater the quality of content. :) Using php, I'm trying to create a script which will delete several lines within a text file (.txt) if required, based upon whether the line starts with a 0 or a negative number. Each line within the file will always start with a number, and I need to erase all the neutral and/or negative numbers. The main part I'm struggling with is that the content within the text file isn't static (e.g. contain x number of lines/words etc.) Infact, it is automatically updated every 5 minutes with several lines. Therefore, I'd like all the lines containing a neutral or negative number to be removed. The text file follows the structure: -29 aullah1 0 name 4 username 4 user 6 player If possible, I'd like Line 1 and 2 removed, since it begins with a neutral/negative number. At points, there maybe times when there are more than two neutral/negative numbers. All assistance is appreciated and I look forward to your replies; thank you. :) If I didn't explain anything clearly and/or you'd like me to explain in more detail, please reply. :) Thank you.
Example: $file = file("mytextfile.txt"); $newLines = array(); foreach ($file as $line) if (preg_match("/^(-\d+|0)/", $line) === 0) $newLines[] = chop($line); $newFile = implode("\n", $newLines); file_put_contents("mytextfile.txt", $newFile); It is important that you chop() the newline character off of the end of the line so you don't end up with empty space. Tested successfully.
Something on these lines i guess, it is untested. $newContent = ""; $lines = explode("\n" , $content); foreach($lines as $line){ $fChar = substr($line , 0 , 1); if($fChar == "0" || $fChar == "-") continue; else $newContent .= $line."\n"; }
If the file is big, its better to read it line by line as: $fh_r = fopen("input.txt", "r"); // open file to read. $fh_w = fopen("output.txt", "w"); // open file to write. while (!feof($fh_r)) { // loop till lines are left in the input file. $buffer = fgets($fh_r); // read input file line by line. // if line begins with num other than 0 or -ve num write it. if(!preg_match('/^(0|-\d+)\b/',$buffer)) { fwrite($fh_w,$buffer); } } fclose($fh_r); fclose($fh_w); Note: Err checking not included.
file_put_contents($newfile, implode( preg_grep('~^[1-9]~', file($oldfile)))); php is not particularly elegant, but still...
Load whole line into variable trim it and then check if first letter is - or 0. $newContent = ""; $lines = explode("\n" , $content); foreach($lines as $line){ $fChar = $line[0]; if(!($fChar == '0' || $fChar == '-')) $newContent .= $line."\n"; } I changed malik's code for better performance and quality.
Here's another way: class FileCleaner extends FilterIterator { public function __construct($srcFile) { parent::__construct(new ArrayIterator(file($srcFile))); } public function accept() { list($num) = explode(' ', parent::current(), 2); return ($num > 0); } public function write($file) { file_put_contents($file, implode('', iterator_to_array($this))); } } Usage: $filtered = new FileCleaner($src_file); $filtered->write($new_file); Logic and methods can be added to the class for other stuff, such as sorting, finding the highest number, converting to a sane storage method such as csv, etc. And, of course, error checking.