开发者

Problem using PHP to open text file - blank spaces are removed

I'm trying 开发者_运维技巧to open and process ASCII files using PHP, but am having problems. The problem is that the blank spaces are removed, which I don't want to have happen, since the files are fixed width.

The PHP script I used is this:

$myFile = Test.SEG";
$file_handler = fopen ($myFile, r) or die ("Can't open SEG File.");
while (!feof($file_handler))
    {
    $dataline = fgets($file_handler);
    echo $dataline, "<br />";
    }

I tried pasting samples of the original file in here, but the spaces were removed here as well!

At this stage I'm just building the script in steps, getting one step working at a time, but this is as far as I've gotten. I plan to use substr() on '$dataline' to pick out the fields I need.

Any suggestions on how to keep the spaces intact? Something tells me it's something to do with encoding, but I don't know for sure.

Thanks!


I don't think they are really removed. Try adding <pre> before and </pre> after to find out if they are really gone. I think it is just the HTML rendering that makes them appear gone.


It has nothing to do with encoding, and everything with the fact that your browser is treating the output as HTML. Either send a header to have the browser treat it as text/plain, or put it in a <pre> block.


Browser won't care about more than one space, but if you see the source, you will see the correct output. If I understand correctly, you should replace all the space chars with 'nbsp' for example.

Edited: pre is better as someone wrote here


A browser will not preserve whitespace when rendering text on an HTML page. Consequently, newlines and tabs are ignored while multiple spaces are collapsed to a single space.

If you view the source of your page you can see the original whitespace. A <pre> block will tell the browser to preserve the whitespace when displaying the text on the page. Take this example:

this is   just


a test
of   some

    data.

I tested your code locally and there seem to be a few mistakes in it.

<?php

$myFile = "Test.SEG"; // missing opening quote

$file_handler = fopen($myFile, "r") // missing quotes for read mode flag
                or die ("Can't open SEG File.");

while (!feof($file_handler)) {
  $dataline = fgets($file_handler);
  echo $dataline; // fgets keeps the newline,
                  // so you do not need to output another
}


Try this (without the space between "&" and "nbsp;"):


echo str_replace(' ', '& nbsp;', $dataline)."\n";


You can override pre tag css , white-space: pre-line

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜