PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?php
error_reporting(E_ALL);
$mailFile = "/mail.emlx";
$handle = fopen($mailFile, "r");
if(!$handle)
{
echo "Couldn't open the data file. Try again later.";
exit;
}
$mailLines = fread($handle, filesize($mailFile));
fclose($handle);
echo $mailLines;
?>
When this script runs, the contents of the file are echoed to the screen, but it is all one line. If I view the file in a text editor, it is on multiple lines with carriage returns.
I can attach the file if that would help. I imagine the problem is something to do with the encoding of the file, but I don't know how to change the way fopen() opens the file, if I even can?
@wtf
If I change echo $mailLines; to echo $mailLines[x]; then it prints just a single character rather than a whole line. Doesn't this suggest that the variable is a string, and mailLines[x] is referring to character x of the string rather than line x of an array?
@timvw
Thanks for the suggestion. I don't actually want to echo the whole thing, I was just doing this for testing. I will be extracting individual strings from the file using ereg(). Because the file is being read as a single line, ereg() returns the whole line when it finds a match.
I have just been reading this page about text encoding. If I understand correctly, PHP assumes text will be un Unix encoding with single linefeeds. The page also says that the Mac uses single carriage returns. My PHP server is running on MacOS X. Could this be the problem? If I convert the carriage returns to linefeeds, will that work?
The site I linked above lists this command for converting Mac Newline (CR) to Unix Newline (LF): $mailLines =~ s/\r/\n/g;. What would be the result of doing this? Would I then be able to output $mailLines to an array, with each entry in the array containing one of the lines from mailLines?
I don't actually want to display the variable in the browser. I want the text file to exist in an array, each line of which contains a line of the text file. Then I can address each line as mailLines[x]. Currently, the file is imported as a string in PHP. Echoing, for example, mailLines[3] echoes the fourth character of the file instead of the fourth line.