我想從html表中提取數據到csv。我加載html數據並通過簡單的html dom進行處理。這是我的示例數據通過簡單的html dom從html表中提取數據到csv
<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"
可能嗎?請幫忙。
什麼是你的問題?如果是如何刪除尾部空格,那麼答案是'trim()' – pguardiario