开发者

How to concatenate two strings using fgetcsv and fputcsv?

开发者 https://www.devze.com 2023-02-04 12:31 出处:网络
I\'m creating a script that will read a csv file and display it on a textarea using fgetcsv. $handle = @fopen($filePath, \"r\");
  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 = sp开发者_运维知识库lit("\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!


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消