用php来解析html文件

时间:2011-03-02 17:21:22

标签: php html parsing dom

我正在制作一个php应用程序来解析HTML内容。我需要在php变量中存储某个表列。

这是我的代码:

$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 />';
            }
     }

在每一行中,第一个col是KEY,第二个是VALUE。如何从表中创建键值对并将它们存储为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()进行清理,但它仍然存在......

1 个答案:

答案 0 :(得分:2)

您要加载的HTML是什么?我假设它很简单:

<table>
    <tr>
        <td>heading</td>
        <td>heading</td>
    </tr>
    <tr>
        <td>key</td>
        <td>value</td>
    </tr>
</table>

看起来跳过了第一个tr(标题),然后您只想将2个列配对为KEY =&gt;值;

$cols = $row->getElementsByTagName('td');
$key = $cols->item(0)->nodeValue; // string(3) "key"
$val = $cols->item(1)->nodeValue; // string(5) "value"

上面的代码将返回您想要的项目。