如何将html表列转换为表行,dom对象,php

时间:2013-03-06 12:35:31

标签: php dom

我有一个html表,我想将其列转换为行。列可以包含计划文本,表单元素(输入,选择,复选框)或html标记(span,div)。请考虑以下html:

<html>
  <body>
    <table>
      <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
        <td>Cell 3</td>
      </tr>
      <tr>
        <td>Cell 4</td>
        <td>Cell 5</td>
        <td>Cell 6</td>
      </tr>
    </table>
  </body>
</html>
在dom操作之后我需要以下内容:

<html>
  <body>
    <table>
      <tr>
        <td>Cell 1</td>
      </tr>
      <tr>
        <td>Cell 2</td>
      </tr>
      <tr>
        <td>Cell 3</td>
      </tr>
      <tr>
        <td>Cell 4</td>
      </tr>
      <tr>
        <td>Cell 5</td>
      </tr>
      <tr>
        <td>Cell 6</td>
      </tr>
    </table>
  </body>
</html>

$rows = $xpath->query('xpath to table/tr');
foreach ($rows as $row){
    $cols = $xpath->query('xpath to table/tr/*');
    $row->parentNode->removeChild($row);
    foreach ($cols as $col){
        $newNode = $this->createElement('tr');
        $newNode->appendChild($col);
        $node->appendChild($newNode);
    }
}
echo $dom->saveHTML();

它的工作正常,但它添加了空行:

<table>
  <tr></tr>
  <tr></tr>
  <tr>
    <td>Cell 1</td>
  </tr>
  <tr>
    <td>Cell 2</td>
  </tr>
<table>

我知道我做错了吗?

2 个答案:

答案 0 :(得分:0)

您可以使用DOM解析HTML和XML,这就是您可以阅读表的方法:

$dom = new DOMDocument;
$dom->loadHTML( $table );
$tds = array();
foreach( $dom->getElementsByTagName( 'td' ) as $td ) {
  $tds[] = $td->nodeValue;
}

打印展平的结构:

foreach($tds as $td){
    print '<td>'.$td.'</td>';
}

答案 1 :(得分:0)

您可以将每个<td>元素移动到其当前祖先<tr>元素的新<table>子元素中:

foreach($xpath->query('//td') as $td)
    $xpath->query('ancestor::table[1]', $td)->item(0)
        ->appendChild($doc->createElement('tr'))->appendChild($td);
{{;;}}

之后,您可以删除所有没有<tr>个孩子的所有<td>元素:

foreach($xpath->query('//tr[0 = count(td)]') as $tr)
    $tr->parentNode->removeChild($tr);
{{;;}}

您的文档现已转换:

<table>
<tr><td>Cell 1</td></tr>
<tr><td>Cell 2</td></tr>
<tr><td>Cell 3</td></tr>
<tr><td>Cell 4</td></tr>
<tr><td>Cell 5</td></tr>
<tr><td>Cell 6</td></tr>
</table>