通过简单的html dom将数据从html表提取到csv

时间:2014-03-12 22:23:25

标签: php html csv simple-html-dom

我想将数据从html表提取到csv。我通过简单的html dom加载html数据和进程。这是我的样本数据

<tr id="ST1" class="foo"><td class="CLASS_0_NO_NEED"><span class="icons">pet</span></td><td class="name"><span class="name_icons">tom</span></td><td class="p_type"><span class="type_icons">cat</span></td><td class="p_sex"><span class="s_icons">male</span></td><td class="p_year"><span class="y_icons">2</span></td>
<td class="p_height"><span class="Height" alt="2|3">3</span></td>
<td class="p_weight"><span class="Weight" alt="3|5">5</span></td>
<td class="CLASS_7_NO_NEED">Close</td></tr>

<tr id="ST2" class="foo"><td class="CLASS_0_NO_NEED"><span class="icons">pet</span></td><td class="name"><span class="name_icons">sam</span></td><td class="p_type"><span class="type_icons">dog</span></td><td class="p_sex"><span class="s_icons">male</span></td><td class="p_year"><span class="y_icons">1</span></td>
<td class="p_height"><span class="Height" alt="4|4.5">4.5</span></td>
<td class="p_weight"><span class="Weight" alt="5|7">7</span></td>
<td class="CLASS_7_NO_NEED">Close</td></tr>

我使用简单的html dom这段代码。

include 'simple_html_dom.php';
$html = file_get_contents('testpet.html');
$html = str_get_html($html);

header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=sample.csv');

$fp = fopen("sample.csv", "w");
foreach($html->find('tr') as $element)
{
  $td = array();
   foreach( $element->find('td') as $row)
  {
    $td [] = $row->plaintext;
  }
  fputcsv($fp, $td);
}
fclose($fp);

$html->clear();
unset($html);

sample.csv的输出不是我真正想要的,因为每个字段都有“$ DATA + space”。

"pet ","tom ","cat ","male ","2 ","3 ","5 ",Close
"pet ","sam ","dog ","male ","1 ","4.5 ","7 ",Close

此外我确实需要一些alt(Height.alt和Weight.alt)值给csv,我不想要一些类(图标)。 filnal cvs应该是这样的。

"tom","cat","male","2","2","3","3","5"
"sam","dog","male","1","4","4.5","5","7"

有可能吗?请帮忙。

1 个答案:

答案 0 :(得分:0)

先生,你不想使用jquery和javascript bcoz就这么简单。

但你可以尝试php函数fputcsv()

示例#1 fputcsv()示例

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>
The above example will write the following to file.csv:
aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""