繁体   English   中英

用php来解析html文件

[英]Using php to parse html document

我正在制作一个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()进行清理但是它仍然存在...

您要加载的HTML是什么? 我假设这是一个简单的事情:

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

看起来第一个tr被跳过(标题),然后你只有2列你想要配对为KEY => VALUE;

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM