سؤال

I am using PHP to read a simple text file with the fgets() command:

$file = fopen("filename.txt", "r") or exit('oops');
$data = "";

while(!feof($file)) {
    $data .= fgets($file) . '<br>';
}

fclose($file);

The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:

$data = str_replace(" ", "&nbsp;", $data);

Not sure where to go from here.

Thanks in advance,

Doug

UPDATE:

The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.

هل كانت مفيدة؟

المحلول

Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:

$file = fopen('file.txt', 'r') or exit('error'); 
$data = '';

while(!feof($file)) 
{
    $data .= '<pre>' . fgets($file) . '</pre><br>'; 
}

fclose($file);

echo $data;

The PRE tag allows you to display $data without parsing it.

نصائح أخرى

Try it with:

$data = preg_replace('/\s+/', '&nbsp;', $data);

fgets should not trim whitespaces.

Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.

$data = file_get_contents("xyz.txt");

$data = str_replace(" ","~",$data);

echo $data;

Hope this helps

I currently have the same requirement and experienced that some characters are written as a tab character.

What i did was:

$tabChar = '&nbsp;&nbsp;&nbsp;&nbsp;';
$regularChar = '&nbsp;'

$file = fopen('/file.txt');
while($line = fgets($file)) {

   $l = str_replace("\t", $tabChar, $line);
   $l = str_replace(" ", $regularChar, $line);
   // ...
   // replacing can be done till it matches your needs

   $lines .= $l; // maybe append <br /> if neccessary

}

$result = '<pre'> . $lines . '</pre>';

This one worked for me, maybe it helps you too :-).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top