Hi I am trying to create some code that first reads the existing contents of the file in and then adds the new line of code on a new line but the code i am using just adds it on the new text on to the already existing line instead of the new line...
Here is the code i am using:
<?php
$id = $_GET['id'];
$userfile = "user1.txt";
$fo = fopen($userfile, 'r') or die("can't open favourites file");
$currentdata = fread($fo, filesize($userfile));
fclose($fo);
$fw = fopen($userfile, 'w') or die("can't open favourites file");
$currentprocessed = "$currentdata\n";
fwrite($fw, $currentprocessed);
fwrite($fw, $id);
fclose($fw);
?>
I have tried a whole range of different ideas but nothing has worked, any help would be appreciated.
Line endings per OS
Unix / Linux
\n
DOS / Windows
\r\n
Invalid
\r and \n\r
The value of PHP_EOL constant depends on the platform php is running on.
It doesn't detect the line-endings in the current file or anything magic.
Instead of appending \n, concatenate the constant PHP_EOL which is always the correct newline character for the current platform.
It might also be an issue with the program you're using to open the text file with. For instance, Notepad on Windows is incapable of understanding unix style newlines.
I ran into this same issue. What application are you using to read the file? I found that for some reason Notepad (my default for .txt files) didn't recognize the "\n\r" escape characters. I opened my .txt file that I was writing to using Notepad++, Atom (my text editor of choice), or in a browser and they all showed the line breaks just fine.
Related
I am using urldecode data for writing a content in to a text file, but in that file all the contents are showing together(not aligned expected) in windows notepad(in windows wordpad it is coming correctly), also when i open it in Ubuntu contents are coming correctly(my contents have enter key and spaces some special characters too).
$attachment_file = fopen(Yii::app()->basePath.'/../uploads/attachment'.$user_id.'.txt', "a+") or die("Unable to open file!");
$content = urldecode($note_data["note_data"]);
fwrite($attachment_file,$content);
fclose($attachment_file);
For the quick fix i did
$content = str_replace("\n","\r\n",$content);
but i want to know is there any other methods to do it.
If you are using Linux to create the file, you should manually add this. If you use Windows, You can try str_replace("\n", PHP_EOL, $content) instead.
I don't understand why you are doing urldecode. Maybe you should use something like utf8_decode if you have your data in utf-8 format.
A trivial use of PHP and frwite() to create/write to a text file.
However, is there a way to write a very large text string to a file using fwrite?()? I assume there is, and that it involves some form of buffer management. The PHP docs don't seem to have this covered.
Sample code:
$p = "Some really large string ~ 100-250K in size"
$myFile = "testp.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
set_file_buffer($fh, 1000000);
fwrite($fh, $p);
fclose($fh);
Believe it or not, this simply gets a file with the name of the file inside the file.
Using a much smaller text string, it works as expected. Pointers to what I should do would be useful.
UPDATE:
Some of you are missing that I did try the above with a string of ~100K, and it didn't work. All I got in the output file was the name of the file!!!
thanks
::: 2ND UPDATE....
never mind.. the whole thing was user error... god i need a drink... or sleep!
thanks
php/fwrite works as i thought it would/should.. nothing to see here..!
There is no limit on how much data can be written to a stream (a file handle) in PHP and you do not need to fiddle with any buffers. Just write the data to the stream, done.
So I have a sql database that generates an xml file. This xml file gets put on a webserver and then parsed by a php file. Unfortunately randomly sometimes there will be a line break in the xml file that causes it to be unable to be parsed.
http://imgur.com/jNgiE
As you can see from line 12-14. There is a linebreak. But I have no idea why. And I even wrote a script to remove carriage returns and newline characters but the linebreaks still remain. Anyone have any ideas?
$inputXML = file_get_contents("ukso.xml");
$fixedXML = str_replace("\r","",$inputXML);
$fixedXML = str_replace("\n","",$inputXML);
$fixedXML = str_replace(" ","",$inputXML);
$myFile = "ukso.xml";
print $fixedXML;
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $fixedXML);
fclose($fh);
Your code to remove linebreaks is broken. make the following changes:
$inputXML = file_get_contents("ukso.xml");
$fixedXML = str_replace("\r","",$inputXML);
$fixedXML = str_replace("\n","",$fixedXML); // note: reference the correct variable here
$fixedXML = str_replace(" ","",$fixedXML); // and here.
$myFile = "ukso.xml";
print $fixedXML;
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $fixedXML);
fclose($fh);
The code as you have it is only trimming out double spaces.
I see you're using notepad++
Go into view-show symbol-show all characters. That will tell you exactly what characters there are in the file.
It's possible that the line breaks are also due to the line being too long otherwise. XML files are usually designed to have line breaks at the end of tags, and you may be running into a situation where the line length is too long somewhere in one of the programs. (Often they create a fixed buffer and read in as much as possible, and if it's too long the program will chop the line)
My code:
$i = 0;
$file = fopen('ids.txt', 'w');
foreach ($gemList as $gem)
{
fwrite($file, $gem->getAttribute('id') . '\n');
$gemIDs[$i] = $gem->getAttribute('id');
$i++;
}
fclose($file);
For some reason, it's writing \n as a string, so the file looks like this:
40119\n40122\n40120\n42155\n36925\n45881\n42145\n45880
From Google'ing it tells me to use \r\n, but \r is a carriage return which doesn't seem to be what I want to do. I just want the file to look like this:
40119
40122
40120
42155
36925
45881
42145
45880
Thanks.
Replace '\n' with "\n". The escape sequence is not recognized when you use '.
See the manual.
For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").
PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:
Using this will save you extra coding on cross platform developments.
IE.
$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);
If you looped through this twice you would see in 'somefile':
some data
some data
Use PHP_EOL which outputs \r\n or \n depending on the OS.
You can also use file_put_contents():
file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);
I have a php function I wrote that will take a text file and list each line as its own row in a table.
The problem is the classic "works fine on my machine", but of course when I ask somebody else to generate the .txt file I am looking for, it keeps on reading in the whole file as 1 line. When I open it in my text editor, it looks just as how I would expect it with a new name on each line, but its the newline character or something throwing it off.
So far I have come to the conclusion it might have something to do with whatever text editor they are using on their Mac system.
Does this make sense? and is there any easy way to just detect this character that the text editor is recognizing as a new line and replace it with a standard one that php will recognize?
UPDATE: Adding the following line solved the issue.
ini_set('auto_detect_line_endings',true);
Function:
function displayTXTList($fileName) {
if(file_exists($fileName)) {
$file = fopen($fileName,'r');
while(!feof($file)) {
$name = fgets($file);
echo('<tr><td align="center">'.$name.'</td></tr>');
}
fclose($file);
} else {
echo('<tr><td align="center">placeholder</td></tr>');
}
}
This doesn't work for you?
http://us2.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings
What's wrong with file()?
foreach (file($fileName) as $name) {
echo('<tr><td align="center">'.$name.'</td></tr>');
}
From the man page of fgets:
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
Also, have you tried the file function? It returns an array; each element in the array corresponds to a line in the file.
Edit: if you don't have access to the php.ini, what web server are you using? In Apache, you can change PHP settings using a .htaccess file. There is also the ini_set function which allows changing settings at runtime.
This is a classic case of the newline problem.
ASCII defines several different "newline" characters. The two specific ones we care about are ASCII 10 (line feed, LF) and 13 (carriage return, CR).
All Unix-based systems, including OS X, Linux, etc. will use LF as a newline. Mac OS Classic used CR just to be different, and Windows uses CR LF (that's right, two characters for a newline - see why no one likes Windows? Just kidding) as a newline.
Hence, text files from someone on a Mac (assuming it's a modern OS) would all have LF as their line ending. If you're trying to read them on Windows, and Windows expects CR LF, it won't find it. Now, it has already been mentioned that PHP has the ability to sort this mess out for you, but if you prefer, here's a memory-hogging solution:
$file = file_get_contents("filename");
$array = split("/\012\015?/", $file); # won't work for Mac Classic
Of course, you can do the same thing with file() (as has already been mentioned).