代码之家  ›  专栏  ›  技术社区  ›  mrpatg

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

  •  3
  • mrpatg  · 技术社区  · 16 年前

    如何使用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>
    

    然后抓取“标签”和“数据信息”并将它们存储在关联数组中,例如:

    $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 回复  |  直到 16 年前
        1
  •  8
  •   Ivan Nevostruev    16 年前

    在这种情况下,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;
     }
    
        2
  •  0
  •   Erik    16 年前

    我从来没有玩过简单的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上打印一下。

    最终输出将是:

    Array
    (
        [Name] => Stuff
        [Email] => Stuff2
        [Address] => Stuff3
        [Field1] => MoreStuff
        [Field2] => MoreStuff2
        [Field3] => MoreStuff3
    )
    
        3
  •  0
  •   AntonioCS    16 年前

    我决定使用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>
    
    推荐文章