PHP DOM Parser解析html表

时间:2016-11-05 17:15:05

标签: php html parsing dom

如何使用PHP DOM Parser来解析表的内容,所以我得到:

  • 用户名
  • 手机号码
  • 状态

因此我尝试提取的输出将是:

  • randomusername - 0123456789 - active
  • randomusername2 - 0987654321 - active

这是我尝试解析的html(部分内容):

...
<div class="table tbl-process-mobile">
  <div class="table-cn">
    <div class="table-bd">
      <table cellspacing="0" id="idd7">

<thead>
    <tr id="idd9">
        <th scope="col">
          <span>username</span>
        </th>
        <th scope="col">
          <span>status</span>
        </th>

        <th scope="col">        
          <span>prefered number</span>
        </th>

        <th scope="col">
          <span>action</span>
        </th>
    </tr>
</thead>

<tbody id="iddb">
    <tr class="even">
        <td class="even">
            <div>randomusername</div>
        </td><td class="odd">
            <div>0123456789</div>
        </td><td class="even">
            <div>active</div>
        </td><td class="odd">
            <div>
  <span id="iddc" style="display:none"></span>
  <a href="xyz" id="idb2"><span>set number</span></a>
</div>
        </td><td class="even">
            <div>
  <a id="iddd" style="display:none"></a>
  <a href="xyz" class="action-icon-edit" id="idb3" title="change">
    <i>change</i>
  </a>
  <a href="xyz" class="action-icon-delete" id="idb4" title="delete">
    <i>delete</i>
  </a>
</div>
        </td>
    </tr><tr class="odd">
        <td class="even">
            <div>randomusername2</div>
        </td><td class="odd">
            <div>0987654321</div>
        </td><td class="even">
            <div>active</div>
        </td><td class="odd">
            <div>
  <span id="idde" style="display:none"></span>
  <a href="xyz" id="idb5"><span>set number</span></a>
</div>
        </td><td class="even">
            <div>
  <a id="iddf" style="display:none"></a>
  <a href="xyz" class="action-icon-edit" id="idb6" title="change">
    <i>change</i>
  </a>
  <a href="xyz" class="action-icon-delete" id="idb7" title="delete">
    <i>delete</i>
  </a>
</div>
        </td>
    </tr>
</tbody>
</table>
    </div>
  </div>
</div>
...

我已经开始使用一些PHP代码了:

<?php
error_reporting(0);
$matches = array();
$dom = new DOMDocument;

$dom->loadHTMLFile('settings.html');

如何提取值,从这一点解析HTML的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

$field_names = ['username', 'phone', 'status'];
$result = [];

// Search for div tags having tbl-process-mobile class
$containers = $doc->getElementsByTagName('div');
foreach ($containers as $container) {
  if (!isset($container->attributes['class']))
    continue;

  if (false === strpos($container->attributes['class']->value,
    'tbl-process-mobile'))
    continue;

  // Assume that tbody tags are required
  if (!$tbodies = $container->getElementsByTagName('tbody'))
    continue;

  // Get the first tbody (there should not be more)
  if (!$tbodies->length || !$tbody = $tbodies->item(0))
    continue;

  foreach ($tbody->getElementsByTagName('tr') as $tr) {
    $i = 0;
    $row = [];
    $cells = $tr->getElementsByTagName('td');

    // Collect the first count($field_names) cell values as maximum
    foreach ($field_names as $name) {
      if (!$td = $cells->item($i++))
        break;
      $row[$name] = trim($td->textContent);
    }

    if ($row)
      $result []= $row;
  }
}

var_dump($result);

示例输出

array(2) {
  [0]=>
  array(3) {
    ["username"]=>
    string(14) "randomusername"
    ["phone"]=>
    string(10) "0123456789"
    ["status"]=>
    string(6) "active"
  }
  [1]=>
  array(3) {
    ["username"]=>
    string(15) "randomusername2"
    ["phone"]=>
    string(10) "0987654321"
    ["status"]=>
    string(6) "active"
  }
}

没有评论,因为代码是不言自明的。

P.S。:在解析意义上,HTML结构有很多不足之处。

答案 1 :(得分:0)

您可以使用DOMDocument类的选择器方法,例如getElementById()getElementsByTag()来查找目标元素。找到元素后,获取它的文本并存储在数组中。

$trs = $dom->getElementById("iddb")->getElementsByTagName("tr");
$arr = [];
foreach($trs as $key=>$tr){
    $tds = $tr->getElementsByTagName("td");
    $arr[$key] = [
        $tds->item(0)->textContent,
        $tds->item(1)->textContent,
        $tds->item(2)->textContent
    ];
}

检查demo

中的结果

您也可以使用DOMXPath类来查找目标元素。

$xpath = new DOMXPath($dom);
$trs = $xpath->query("//tbody/tr");

答案 2 :(得分:-1)

尝试使用strip_tags

$html='<div class="table tbl-process-mobile">
  <div class="table-cn">
    <div class="table-bd">
      <table cellspacing="0" id="idd7">

<thead>
    <tr id="idd9">
        <th scope="col">
          <span>username</span>
        </th>
        <th scope="col">
          <span>status</span>
        </th>

        <th scope="col">        
          <span>prefered number</span>
        </th>

        <th scope="col">
          <span>action</span>
        </th>
    </tr>
</thead>

<tbody id="iddb">
    <tr class="even">
        <td class="even">
            <div>randomusername</div>
        </td><td class="odd">
            <div>0123456789</div>
        </td><td class="even">
            <div>active</div>
        </td><td class="odd">
            <div>
  <span id="iddc" style="display:none"></span>
  <a href="xyz" id="idb2"><span>set number</span></a>
</div>
        </td><td class="even">
            <div>
  <a id="iddd" style="display:none"></a>
  <a href="xyz" class="action-icon-edit" id="idb3" title="change">
    <i>change</i>
  </a>
  <a href="xyz" class="action-icon-delete" id="idb4" title="delete">
    <i>delete</i>
  </a>
</div>
        </td>
    </tr><tr class="odd">
        <td class="even">
            <div>randomusername2</div>
        </td><td class="odd">
            <div>0987654321</div>
        </td><td class="even">
            <div>active</div>
        </td><td class="odd">
            <div>
  <span id="idde" style="display:none"></span>
  <a href="xyz" id="idb5"><span>set number</span></a>
</div>
        </td><td class="even">
            <div>
  <a id="iddf" style="display:none"></a>
  <a href="xyz" class="action-icon-edit" id="idb6" title="change">
    <i>change</i>
  </a>
  <a href="xyz" class="action-icon-delete" id="idb7" title="delete">
    <i>delete</i>
  </a>
</div>
        </td>
    </tr>
</tbody>
</table>
    </div>
  </div>
</div>';

echo strip_tags($html);

<强>更新

使用getElementsByTagName

解析DOM元素

阅读所有td

$td=$dom->getElementsByTagName('td');

循环读取td并读取div内容

foreach($td as $t){
$div=$t->getElementsByTagName('div');
foreach($div as $d){
    echo $d->textContent;
}

}

上面将获取所有div内容但我们只有特定的div元素,因此我建议您为要检索的div添加一些类或数据属性。然后将if条件放在循环中。在这里,我添加了 数据 类。

 foreach($td as $t){
$div=$t->getElementsByTagName('div');
foreach($div as $d){
    if($d->getAttribute('class')=='data'){
     echo $d->textContent;
   }

}}