0

我有一个 html 表,我想将它的列转换为行。列可以包含计划文本、表单元素(输入、选择、复选框)或 html 标记(跨度、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>

知道我在做什么错吗?

4

2 回答 2

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>';
}
于 2013-03-06T12:48:20.280 回答
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> 
于 2013-03-15T17:48:18.840 回答