如何将这个html数据解析成php数组?

时间:2012-03-23 10:00:59

标签: php html parsing

我以这种形式接收数据,我想将这个html数据解析为php数组。

<table class="qprintable" cellspacing="1" cellpadding="0" border="0" width="600">
<tbody>
<tr>
<td width="300" valign="top">
<table class="qprintable2" cellspacing="0" cellpadding="4" border="0" width="100%">
<tbody>
<tr class="phead">
<td colspan="2">
<b></b>
</td>
</tr>
<tr>
<td valign="top">
<div class="first"></div>
<div></div>
<div>2009jobs.agile@gmail.com</div>
<br>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<br>
<br>
<div></div>
<div class="last"></div>
</td>
<td valign="top">
<div class="first"></div>
<br>
<div></div>
<br>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div class="last">&nbsp;</div>
</td>
</tr>
<tr width="290">
<td valign="top" colspan="2">
<div class="first"></div>
<div></div>
<div class="last"></div>
</td>
</tr>
</tbody>
</table>
</td>
<td width="300" valign="top">
<table class="qprintable2" cellspacing="0" cellpadding="4" border="0" width="100%">
<tbody>
<tr class="phead">
<td colspan="2">
<b></b>
</td>
</tr>
<tr>
<td valign="top">
<div class="first"></div>
<div></div>
<div>aerosoft.career@rediffmail.com</div>
<br>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<br>
<br>
<div></div>
<div class="last"></div>
</td>
<td valign="top">
<div class="first"></div>
<br>
<div></div>
<br>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div class="last">&nbsp;</div>
</td>
</tr>
<tr width="290">
<td valign="top" colspan="2">
<div class="first"></div>
<div></div>
<div class="last"></div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>

2 个答案:

答案 0 :(得分:1)

这个非常丑陋的表...但如果你不安,他们就是3个解决方案

使用http://simplehtmldom.sourceforge.net/

写了这个简单的代码:

    var_dump(parseUglyTable($table)) ;
    function parseUglyTable($table)
    {
        $html = str_get_html($table);
        $data = array(); 

        foreach($html->find('tr') as $row) {


            if($row)
            {
                $td = $row->find('td',0);

                $text = str_replace(array("<div>","</div>","&nbsp;"), "\n", $td->plaintext);
                $text = explode("\n", $text);

                foreach($text as $value)
                {
                    $value  = trim($value);
                    if(empty($value))
                        continue ;

                    $data[]  = $value ;
                }
            }
        }
        return $data;
    }

输出

    array
    0 => string '2009jobs.agile@gmail.com' (length=24)
    1 => string '2009jobs.agile@gmail.com' (length=24)
    2 => string 'aerosoft.career@rediffmail.com' (length=30)

使用 preg_match_all

我认为它唯一的电子邮件地址存在于那个丑陋的表格中......有关更多信息,请参阅http://php.net/manual/en/function.preg-match-all.php更高效

为什么要使用坦克或家伙杀死老鼠 ???只要求JSON或XML格式

我希望这会有所帮助

由于 :)

答案 1 :(得分:0)

从中创建一个字符串,php通过“\ n”

将其爆炸