将html代码直接保存到CSV文件而无需解释(无格式化)

时间:2015-05-31 12:03:04

标签: php html css csv

我正在尝试将html代码直接保存到csv文件中。但是当我保存html格式并保存到csv而不显示HTML代码时:

HTML代码我试图保存为CSV:

<h3 style="text-align:justify">GREAT VISUAL</h3> 
<div style="line-height: 20.7999992370605px; text-align: justify;">SOME TEXT SOME TEXT SOME TEXT SOME TEXT SOME TEXT SOME TEXT </div>

它应该保存html,因为它不像:

&#34;伟大的视觉 一些文字有些文字有些文字有些文字有些文字和#34;

我使用的PHP代码是:

$array = array();
$sub = array();
$sub['Description_1'] = str_replace(array("\r", "\n", "\t"), "", $html1);
$sub['Description_2'] = str_replace(array("\r", "\n", "\t"), "", $html2);

function cleanData(&$str) {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if (strstr($str, '"'))
      $str = '"' . str_replace('"', '""', $str) . '"';
}

$name = date("F-j-Y-g-i-s-a") . '-OutPut';
$filename = $name . ".xls";

header('Content-Encoding: UTF-8');
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel;charset=UTF-8");
$flag = false;
foreach (array_filter($array) as $row) {
   if (!$flag) {
     // display field/column names as first row
     echo implode("\t", array_keys($row)) . "\n";
     $flag = true;
   }
   array_walk($row, 'cleanData');
   echo implode("\t", array_values($row)) . "\n";
}
exit;

请有人帮帮我吗?我在互联网上尝试了很多解决方案但找不到任何有效的例子。

1 个答案:

答案 0 :(得分:1)

简单的解决方案。为什么这个庞大而无用的代码用于创建CSV? 试试这个。

$name = date("F-j-Y-g-i-s-a") . '-OutPut';

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=$name.csv");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies

function outputCSV($data) {
    $output = fopen("php://output", "w");
    foreach ($data as $row) {
        fputcsv($output, $row); // here you can change delimiter/enclosure
    }
    fclose($output);
}

outputCSV($array);