我正在製作一個PHP應用程序來解析HTML內容。我需要在php變量中存儲某個表列。使用PHP解析HTML文檔
這裏是我的代碼:
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
$flag=0;
foreach ($rows as $row)
{
if($flag==0) $flag=1;
else
{
$cols = $row->getElementsByTagName('td');
foreach ($cols as $col)
{
echo $col->nodeValue; //NEED HELP HERE
}
echo '<hr />';
}
}
在每一行中,第一個關口是關鍵,二是價值問題。如何從表中創建鍵值對並將它們作爲數組存儲在php中。
我嘗試了很多事情,但每次我只是得到DOMElement Object()
作爲價值。
任何幫助深表感謝......的要求
HTML:
<table align='center' border='0' cellpadding='0' cellspacing='0' style='border-collapse: collapse' width='780' height=100%>
<tr><td height=96% align=center><BR><BR>
<html>
<head>
</head>
<body style="background:url(uptu_logo1.gif); background-repeat:no-repeat; background-position:center">
<p align="center" style="font-size:18px"><span style='font-size:20px'>this text is unimportant gibberish that is not required by my app</span><br/><span style='font-size:16px'>this text is unimportant gibberish that is not required by my app</span><br/><u>B.Tech. Third Year Result 2009-10. this text is unimportant gibberish that is not required by my app</u></p>
<br/>
<table align="center" border="1" cellpadding="0" cellspacing="0" bordercolor="#E3DDD5" width="700" style="border-collapse: collapse; font-size: 11px">
<tr>
<td width="50%"><b>Name:</b></td>
<td width="50%">John Fernandes </td>
</tr>
<tr>
<td><b>Fathers Name:</b></td>
<td>Caith Fernandes </td>
</tr>
<tr>
<td><b>Roll No:</b></td>
<td>0702410099</td>
</tr>
<tr>
<td><b>Status:</b></td>
<td>REGULAR </td>
</tr>
<tr>
<td><b>Course/Branch:</b></td>
<td>B. Tech. </td>
</tr>
<tr>
<td><b>Institute Name</b></td>
<td>Imperial College of Science and Technology</td>
</tr>
</table>
我的PHP代碼輸出:
Name:John Fernandes <hr />
Fathers Name:Caith Fernandes <hr />
Roll No:0702410099<hr />
Status:REGULAR <hr />
Course/Branch:B. Tech. Computer Science and Engineering (10)<hr />
Imperial College of Science and Technology<hr />
還怎麼擺脫這種很傻嗎?我在原始HTML中看到 ,所以我嘗試使用PHP函數進行消毒html_entity_decode()
但是它仍然存在...
不應該是'$ dom = new domDocument;'是'$ dom = new DOMDocument();'? – 2011-03-02 17:23:57
@Rocket PHP中的類名不區分大小寫,括號對於沒有任何參數的構造函數是可選的。 – lonesomeday 2011-03-02 17:25:19
你可以包含HTML嗎?還有,'''cols = $ row-> getElementsByTagName('td');'''總是隻返回2列? – McHerbie 2011-03-02 17:25:40