如何使用PHP解析一个非常简单的表

时间:2010-12-19 11:05:15

标签: php

亲爱的社区,祝你好运!

我需要构建一个解析一个非常简单的表的内容的函数 (有一些标签和值)请参阅下面的网址。我用各种方法来解析html源代码。但这个有点棘手!查看我要解析的目标 - 它有一些invaild标记:

目标:http://www.schulministerium.nrw.de/BP/SchuleSuchen?action=644.0013008534253&SchulAdresseMapDO=194190

我试过这个

<?php
require_once('config.php'); // call config.php for db connection
$filename = "url.txt"; // Include the txt file which have urls
$each_line = file($filename);
foreach($each_line as $line_num => $line)
{
    $line = trim($line);
    $content = file_get_contents($line);
    //echo ($content)."<br>";
    $pattern = '/<td>(.*?)<\/td>/si';
    preg_match_all($pattern,$content,$matches);

    foreach ($matches[1] as $match) {
        $match = strip_tags($match);
        $match = trim($match);
        //var_dump($match);
        $sql = mysqli_query("insert into tablename(contents) values ('$match')");
        //echo $match;
    }
}
?>

嗯 - 第7-11行中查看正则表达式:它不匹配!

Conclusio:我必须重做此脚本的解析器部分。我需要解析一些不同的 - 因为parsercode与目标不完全匹配。它旨在取回表格的结果。

有人可以帮助我获得更好的正则表达式 - 或者更好的方法来解析这个网站...... 任何和所有的帮助将大大鼓励。

问候 零

2 个答案:

答案 0 :(得分:0)

你可以使用撕开桌子 preg_split('/<td width="73%">&nbsp;/', $str, -1);(注意;我没有打扰转义字符)

你想放弃第一个条目。现在你可以使用stripos和substr来删除所有内容。

这是一个基本设置!你将不得不对它进行微调,但我希望这可以让你了解我的方法。

答案 1 :(得分:0)

正则表达并不总能提供完美的结果。使用任何HTML解析器都是个好主意。 Gordon's Answer中描述了许多HTML解析器。

我过去曾使用Simple HTML DOM Parser,它对我有用。

例如:

// Create DOM from URL or file
$html = file_get_html('http://www.example.com/');

// Find all <td> in <table> which class=hello 
$es = $html->find('table.hello td');

// Find all td tags with attribite align=center in table tags 
$es = $html->find('table td[align=center]');