Problem using PHP to open a text file - spaces removed

I'm trying to open and process ASCII files using PHP, but I'm having problems. The problem is that empty spaces are removed, which I don't want to have since the files are of fixed width.

I am using PHP script:

$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 here, but spaces were removed here too!

At this point, I'm just building the script step by step, taking one step, working at the same time, but that's as far as I got it. I am planning to use substr () on '$ dataline' to select the fields I need.

Any suggestions on how to keep the space safe and sound? Something tells me it has to do with encoding, but I don't know for sure.

Thanks!

+2


a source to share


6 answers


I don't think they are really removed. Try adding <pre>

before and </pre>

to see if they're really gone. I think this is just HTML rendering making them disappear.



+14


a source


This has nothing to do with encoding, and all with the assumption that your browser treats the output as HTML. Either send a header for the browser to treat it like text/plain

, or put it in a block <pre>

.



+3


a source


The browser will not have more than one space, but if you see the source, you will see the correct output. If I understand correctly, you should replace all space characters with "nbsp" for example.

Edited: pre is better as someone wrote here

0


a source


The browser will not preserve whitespace when rendering text on an HTML page. Consequently, newlines and tabs are ignored and multiple spaces collapse into one space.

If you look at the source of your page, you can see the original whitespace. The block <pre>

tells the browser to preserve spaces when displaying text on the page. Take this example:

this is just


a test
of some

    data.

I tested your code locally and there seemed to be a few bugs 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
}

      

0


a source


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


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

      

0


a source


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

0


a source







All Articles