从MYSQL导出到Excel PHP时删除HTML标记

时间:2014-06-16 23:49:00

标签: php html excel export

我正在寻找与导出到Excel时从MYSQL数据库字段中的字段中删除HTML标记相关的帮助。

当我出口时,我会看到

<BR>Testing actions and comments box

我的代码

$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=excel.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }   

2 个答案:

答案 0 :(得分:0)

HTML无法使用正则表达式进行解析:Using regular expressions to parse HTML: why not?

我建议使用库进行HTML解析。那里有免费的,例如http://htmlpurifier.org/

答案 1 :(得分:0)

此问题已经多次回答:remove html tags

但有点详细,你可以在下面看到。

基于官方PHP文档:http://www.php.net//manual/en/function.strip-tags.php

你应该使用剥离标签:

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>

输出:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>