Home > Net >  Remove white space from text file with line breaks
Remove white space from text file with line breaks

Time:09-11

I have a large file with line breaks and spaces. The file has text like as follows

Ampex 

Baofeng 

JBL 

Pioneer 

Sony 

1 BY ONE 

To read the file i wrote this

$array = explode("\n", file_get_contents('brands.txt'));

foreach($array as $line) {
    
    $html_code = '<div >
  <input  type="radio" name="exampleRadios" id="exampleRadios1" value="option1" checked>
  <label  for="exampleRadios1">'.
     $line
    .'<span >1</span>
  </label>
</div>';
echo $html_code;

echo '<pre>';
//print_r($line);
echo '</pre>';
}

however my html output has an extra radio with value 1 after output the correct value. How can i output the correct value without the 1 showing as a radio button value?

enter image description here

CodePudding user response:

Use file() instead, as that will load the contents into an array with every line as a separate array item by default.

It also supports a couple of flags that are convenient here, like telling it to skip empty lines:

$array = file('brands.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);

As you might have guessed, the flag FILE_SKIP_EMPTY_LINES will make sure that it skips empty lines.

I also added the flag FILE_IGNORE_NEW_LINES. Without that, the linebreaks/new lines at the end of each element will remain.

  •  Tags:  
  • php
  • Related