使用php和regex获取标签和数据并存储为关联数组

时间:2010-01-25 08:20:15

标签: php regex

我如何使用正则表达式在页面中查找此表(需要按名称查找):

<table id="Table Name">
<tr><td class="label">Name:</td>
<td class="data"><div class="datainfo">Stuff</div></td></tr>
<tr><td class="label">Email:</td>
<td class="data"><div class="datainfo">Stuff2</div></td></tr>
<tr><td class="label">Address:</td>
<td class="data"><div class="datainfo">Stuff3</div></td></tr>
</table>
<table id="Table Name 2">
<tr><td class="label">Field1:</td>
<td class="data"><div class="datainfo">MoreStuff</div></td></tr>
<tr><td class="label">Field2:</td>
<td class="data"><div class="datainfo">MoreStuff2</div></td></tr>
<tr><td class="label">Field3:</td>
<td class="data"><div class="datainfo">MoreStuff3</div></td></tr>
</table>

然后抓住“labels”和“datainfo”并将它们存储在一个关联数组中,例如:

$table_name[name] //Stuff
$table_name[email] //Stuff2
$table_name[address] //Stuff3

$table_name2[field1] //MoreStuff
$table_name2[field2] //Morestuff2
$table_name2[field3] //Morestuff3

3 个答案:

答案 0 :(得分:8)

在这种情况下,Regexp是一个糟糕的解决方案。请改用Simple HTML Parser

<强>更新 这是函数:

 $html = str_get_html($html);
 print_r(get_table_fields($html, 'Table Name'));
 print_r(get_table_fields($html, 'Table Name 2'));

 function get_table_fields($html, $id) {
     $table = $html->find('table[id='.$id.']', 0);
     foreach ($table->find('tr') as $row) {
         $key = $row->find('td', 0)->plaintext;
         $value = $row->find('td', 1)->plaintext;
         ## remove ending ':' symbol
         $key = preg_replace('/:$/', '', $key);
         $result[$key] = $value;
     }
     return $result;
 }

答案 1 :(得分:0)

我从未玩过简单的HTML解析器,但我非常喜欢PHP的内置SimpleXML。这完成了同样的事情。

$XML = simplexml_load_string(file_get_contents('test_doc.html'));

$all_labels =  $XML->xpath("//td[@class='label']");
$all_datainfo = $XML->xpath("//div[@class='datainfo']");

$all = array_combine($all_labels,$all_datainfo);
foreach($all as $k=>$v) { $final[preg_replace('/:$/', '', (string)$k)] = (string)$v; }

print_r($final);

如果你想知道我为什么要将所有内容转换为(字符串),请在$ all上执行print_r。

最终输出将是:

Array
(
    [Name] => Stuff
    [Email] => Stuff2
    [Address] => Stuff3
    [Field1] => MoreStuff
    [Field2] => MoreStuff2
    [Field3] => MoreStuff3
)

答案 2 :(得分:0)

我决定使用PHP DOMDocument类

创建代码
<?php 

$dom = new DOMDocument();

$dom->loadHTML(file_get_contents('stackoverflow_table.html'));

$count = 0;
$data = array();

while (++$count) {
  $tableid = 'Table Name' . ($count > 1 ? ' ' . $count : ''); //getting the table id  
  $table = $dom->getElementById($tableid);
  if ($table) {
    $tds = $table->getElementsByTagName('td');

    if ($tds->length) { //did I get td's? 
      for ($i = 0, $l = $tds->length;$i < $l; $i+=2) { 
        $keyname = $tds->item($i)->firstChild->nodeValue; //get the value of the firs td
        $value = null;
        if ($tds->item($i+1)->hasChildNodes()) //check if the 2º td has children (the div) (this might always be true because of whitespace)
          $value = $tds->item($i+1)->childNodes->item(1)->firstChild->nodeValue; //Get the div value (which is the second, because of whitespace)

        $data[$keyname] = $value;
      }
    }
  }
  else //there is no table
    break;
}

//should present the format you wanted :)
var_dump($data);

这是我为此创建的html文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Expires" content="Fri, Jan 01 1900 00:00:00 GMT">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Lang" content="en">
<meta name="author" content="">
<meta http-equiv="Reply-to" content="">
<meta name="generator" content="">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="creation-date" content="11/11/2008">
<meta name="revisit-after" content="15 days">
<title>Example</title>
<link rel="stylesheet" type="text/css" href="my.css">
</head>
<body>
<table id="Table Name">
    <tr>
        <td class="label">Name:</td>
        <td class="data">
            <div class="datainfo">Stuff</div>
        </td>
    </tr>
    <tr>
        <td class="label">Email:</td>
        <td class="data">
            <div class="datainfo">Stuff2</div>
        </td>
    </tr>
    <tr>
        <td class="label">Address:</td>
        <td class="data">
            <div class="datainfo">Stuff3</div>
        </td>
    </tr>
</table>
<table id="Table Name 2">
    <tr>
        <td class="label">Field1:</td>
        <td class="data">
            <div class="datainfo">MoreStuff</div>
        </td>
    </tr>
    <tr>
        <td class="label">Field2:</td>
        <td class="data">
            <div class="datainfo">MoreStuff2</div>
        </td>
    </tr>
    <tr>
        <td class="label">Field3:</td>
        <td class="data">
            <div class="datainfo">MoreStuff3</div>
        </td>
    </tr>
</table>  
</body>
</html>