1

I am trying to read in a text file line by line but it truncates the line to where all spaces get reduced to one space. Is there a way to read in a file without truncating extra spaces?

        # read file
        $myfile = fopen($target_file, "r") or die("Unable to open file!");
        while(!feof($myfile)) {

            # add line to array
            $line[$linenum] = fgets($myfile, 100);

            # display line
            echo $line[$linenum] . "</br></br>";

            # increment counter
            $linenum = $linenum + 1;

        }
John Edward Law
  • 121
  • 1
  • 9
  • 8
    you are outputting html. browsers will collapse multiple whitespaces into a single one. that's not php's problem. That's your display environment's. either use `
    `, or do something like space->  string conversions. and note that the spaces are **NOT** truncated. they're still there. it's your browser LYING to you. do a 'view source' and you'll see them.
    – Marc B Jul 19 '16 at 19:18
  • https://www.w3.org/TR/REC-html40/struct/text.html#h-9.1 – AbraCadaver Jul 19 '16 at 19:23
  • As mentioned by @MarcB. Either use `
    ` - this has a bit of a consoley type of formatting though or if that's an issue you can always use a non-breaking space ` `.
    – dokgu Jul 19 '16 at 19:26
  • 2
    Possible duplicate of [Multiple Spaces Between Words in HTML without  ](http://stackoverflow.com/questions/4503001/multiple-spaces-between-words-in-html-without-nbsp) – chris85 Jul 19 '16 at 19:35
  • Anayway, you have a typo: replace `` with `
    `
    – rap-2-h Jul 19 '16 at 21:09

1 Answers1

0

Perhaps you may want to try another approach using a combination of file_get_contents(), preg_split(), foreach Loop and conditional logic. The Commented Code-Excerpt below demonstrates how:

    <?php

        // THE FILE TO BE READ:
        $targetFile             = __DIR__ . "/some-file.txt";

        // VEER OFF THE USUAL FILE PROCESSING FUNCTIONS... GO NUTS ;-)
        // GET THE CONTENTS OF THE FILE & STORE IT IN A VARIABLE (IF IT EXISTS)
        $strFileContents        = null;
        $arrFileLines           = array();
        if(file_exists($targetFile)){
            $strFileContents    = file_get_contents($targetFile);
        }

        // EVERY LINE IN A FILE IS TERMINATED BY A NEW LINE CHARACTER (\n): WE KNOW THAT
        // SO WE SPLIT THE CONTENTS OF THE FILE USING THIS KNOWLEDGE...
        if(!is_null($strFileContents)){
            $arrFileLines   = preg_split("#\n#", $strFileContents);

            // NOW LOOP THROUGH EACH LINE AND ECHO THE CONTENT...
            if(!empty($arrFileLines)){
                foreach($arrFileLines as $iLineNumber=>$strLineText){
                    echo $strLineText . "<br /><br />";
                }
            }
        }

Hope this provide an alternative...

Cheers and good luck...

Poiz
  • 7,611
  • 2
  • 15
  • 17