2014-03-12 17 views
0

我想從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" 

可能嗎?請幫忙。

+0

什麼是你的問題?如果是如何刪除尾部空格,那麼答案是'trim()' – pguardiario

回答

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""" 
+0

也許我沒有說清楚。 我的程序是 1.加載一個html文件「petdata.html」> 2.簡單的dom數據庫> 3.輸出cvs – usr8655586

+0

是啊,它得到它的先生尋找它。問題是,不同的網站給予不同的方式。 –