Question

  1. I'm creating a script that will read a csv file and display it on a textarea using fgetcsv.

      $handle = @fopen($filePath, "r");
    
      if ($handle)
      {
         while (($buffer = fgetcsv($handle, 1000,",")) !== false) 
         {
              foreach($buffer as $buff){
                 echo $buff."\n";
              }
    
         }
      }      
    
  2. The format of the csv is

    "line1-content1","line1-content2"
    "line2-content1","line2-content2"

  3. Using fgetcsv, the content will display inside the textarea without double-quote and comma. Can I format it so that it will also display the duoble quotes and comma?

  4. Then upon saving it using fputcsv

    $file_to_load = $_GET['filepath'];
    
    $filePath = $dir.$file_to_load;
    
    $trans = trim($_POST['txtarea']);
    $keyarr = split("\n",$trans);
    
    $fp = fopen($filePath, 'w');
    foreach (array ($keyarr) as $fields) {
      fputcsv($fp, $fields);
    }
    
    fclose($fp);
    
  5. Looking on the csv file, it saved the csv but displays it like this

    "line1-content1
    ","line1-content2
    ","line2-content1
    ","line2-content2"

  6. It separates the "line1-content1" and "line1-content2" into two lines and put a comma after the end of every line.

  7. Now I want to keep the formatting of #2. How will I code it?

Can you guide me into the right direction? Thanks!

Was it helpful?

Solution

Sounds like you want to display the actual raw CSV text, not the parsed data within the CSV. Instead of using fgetcsv(), just use fgets() and you'll get the text line without any parsing, preserving the quotes and commas.

As for fputcsv, it's going to write out what you pass into it, so make sure that whatever's coming back from the form is cleaned up (e.g. extra line breaks stripped out).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top