csv export form database [closed]

倖福魔咒の 提交于 2019-12-25 18:52:33

问题


When I export my data from my db, I have a fields called description (inside will can a html tag like <br /><img ....);

When I export when I read this field my cvs stop to work correctly. I do not see inside my function what's happen. It seems when it read something like that <br /> it creates 2 cel one for <br and another for /> for example

Thank you.

  $Qproducts = $this_Db->prepare('select p.*,
                                                       pd.* 
                                                from :table_products p,
                                                      :table_products_description pd
                                                 where p.products_id = pd.products_id
                                                 and language_id = :language_id                                                 
                                                ');
        $Qproducts->bindInt('language_id', $language_id);
        $Qproducts->execute();

        while ($Qproducts->fetch()) {
          $csv[] = [
            'products_id' => $Qproducts->valueInt('products_id'),
 'products_description' => $Qproducts->value('products_description'),
   ];
        }

        ob_clean();

        if ($output == 'screen') {
          header('Content-Type: text/plain; charset=utf-8');
        } else {
          header('Content-Type: application/csv; charset=utf-8');
          header('Content-Disposition: attachment; filename=products-' . $language_id . '.csv');
        }

 echo ImportExportAdmin::csvEncode($csv, $delimiter, $enclosure, $escapechar, null, "\r\n");




public static function csvEncode(array $array, string $delimiter=',', $enclosure='"', $escape='"', $charset='utf-8', string $eol="\r\n") {
  $output = '';

  // Collect columns
  $columns = [];

  foreach ($array as $row) {
    foreach (array_keys($row) as $column) {
      if (!in_array($column, $columns)) $columns[] = $column;
    }
  }

  // Collect rows and order by column order
  foreach (array_keys($array) as $row) {
    $line = [];
    foreach ($columns as $column) {
      $line[$column] = isset($array[$row][$column]) ? $array[$row][$column] : '';
    }
    $array[$row] = $line;
  }

  // Prepend column header
  array_unshift($array, array_combine($columns, $columns));

  // Build output
  foreach ($array as $row) {
    foreach (array_keys($row) as $column) {
      if (strpbrk($row[$column], $delimiter . $enclosure . $escape."\r\n") !== false) {
        $row[$column] = $enclosure . str_replace($enclosure, $escape . $enclosure, $row[$column]) . $enclosure;
      }
    }

    $output .= implode($delimiter, $row) . $eol; // Don't use fputcsv as EOL and escape char can not be customized
  }

  return preg_replace('#(\r\n|\r|\n)#', $eol, $output);
}

来源:https://stackoverflow.com/questions/59431420/csv-export-form-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!