سؤال

I have created a form which utilizes a .txt file to pull the names of the EMPLOYEES from and breaks them up in the SELECT form option using the PHP explode function.

<select name="FakeName" id="Fake-ID" aria-required="true" required>
 <option value=""></option>
  <?php
   $options=nl2br(file_get_contents("employees.txt"));
   $options=explode("<br />",$options);

   for($i=0;$i<count($options);$i++)
   {
    echo "<option value='".$options[$i]."'>".$options[$i]."</option>";
   }
 ?>
</select>

The .txt file appears as such:

Name 1
Name 2
Name 3
ETC

Now this works in the form on the site and properly breaks it up and all looks fine. However, when the results are submitted into a SPREADSHEET (in this case a GOOGLE SPREADSHEET) the output includes the "break" and thus it goes into the spreadsheet in a format similar to:

Row 1: Name 1
Row 2:
       Name 2
Row 3:
       Name 3
Row 4:
       ETC

I am trying to figure out how to change the code or something so that the delimiter itself does not submit as part of the results. NOTE: Using any delimiter submits. I have tried "\" or ";" and it submits with results.

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

المحلول

Instead of adding the line breaks with nl2br() and then removing the line breaks with explode(), try using the line break character '\r' or '\n' or '\r\n'.

<?php
    $options= file_get_contents("employees.txt");
    $options=explode("\n",$options);        // try \r as well.

    foreach ($options as $singleOption){
        echo "<option value='".$singleOption."'>".$singleOption."</option>";
    }

 ?>

This could also fix the issue if the problem was due to Google Spreadsheets reading the line breaks.

نصائح أخرى

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r");
if ($fh) {
    while (($line = fgets($fh)) !== false) {
        $line = trim($line);
        echo "<option value='".$line."'>".$line."</option>";
    }
} else {
    // error opening the file, do something
}

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

<select name="FakeName" id="Fake-ID" aria-required="true" required>

<?php
$options=nl2br(file_get_contents("employees.txt"));
$options=explode("<br />",$options); 
foreach ($options as $item_array)
{
echo "<option value='".$item_array"'>".$item_array"</option>";
 }
?>
</select>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top