我有一个数据库表,它包含以下一列数据格式。在php中解析HTML表格
<table cellspacing="1" cellpadding="0" border="0" width="395">
<tbody>
<tr>
<td valign="top" width="135">
<p>Calories (kcal)<br>Energy (kj)<br>Fats<br>Carbohydrates<br>Protein<br></p>
</td>
<td valign="top">
<p>178<br>748<br>0 g<br>9.6 g<br>0.1 g<br></p>
</td>
<td valign="top" width="135">
<p>Fiber<br>Sugars<br>Cholesterol<br>Sodium<br>Alcohol<br></p>
</td>
<td valign="top">
<p>0 g<br>-<br>0 mg<br>-<br>26.2 g<br></p>
</td>
</tr>
</tbody>
</table>
我要让这对于Calories
,Fats
,Carbohydrates
和Protein
单独的列另一个数据库。 要分离这些数据,我需要从旧数据库中提取数据并像这样解析它。
$qry = "SELECT * FROM table";
$res = $mysqli->query($qry);
// new dom object
$dom = new DOMDocument();
while ($row = $res->fetch_assoc()) {
$html = @$dom->loadHTML($row['columndata']);
//the table by its tag name
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
foreach ($rows as $row)
{
$cols = $row->getElementsByTagName('td');
echo $cols->item(0)->nodeValue.'<br />';
echo $cols->item(1)->nodeValue.'<br />';
}
}
此输出以下:
Calories (kcal)Energy (kj)FatsCarbohydratesProtein
1787480 g9.6 g0.1 g
我无法单独输出字符串中有新的数据库中正确列值。
例如,我想有值178
在Calories
列,在Fats
列0 g
等
你是什么意思“解析基于HTML标签的数据”? – Preetam 2013-04-30 08:31:04
你想要什么输出? – Waygood 2013-04-30 08:32:31
'nodeValue'删除所有的标签,你想要的东西像Javascript的'innerHTML'。 DOMDocument API没有这个,你需要编写它。在http://php.net/manual/en/class.domelement.php – Barmar 2013-04-30 08:36:51