使用PHP自动将HTML表格转换为CSV? [英] Converting HTML Table to a CSV automatically using PHP?
本文介绍了使用PHP自动将HTML表格转换为CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是需要在csv使用PHP自动转换这个html表。
有人可以提供任何想法如何做到这一点吗?
谢谢。
I am just in need to convert a this html table automatically in csv using PHP. Can someone provide any idea how to do this? Thanks.
$table = '<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>';
伙计,我只需要 $ table .csv 文件,它可以使用一些PHP函数自动生成。我们可以将该csv文件的路径定义为 / test / home / path_to_csv
Guys, I just need $table to convert in only .csv file, which could be automatically generated using some PHP function. We can define path for that csv file to /test/home/path_to_csv
推荐答案
str_get_html
http://simplehtmldom.sourceforge.net/
include "simple_html_dom.php";
$table = '<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>';
$html = str_get_html($table);
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=sample.csv');
$fp = fopen("php://output", "w");
foreach($html->find('tr') as $element)
{
$td = array();
foreach( $element->find('th') as $row)
{
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
$td = array();
foreach( $element->find('td') as $row)
{
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
这篇关于使用PHP自动将HTML表格转换为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文