简体   繁体   中英

How to convert html table columns to table rows, dom object, php

I've an html table and i want to convert its columns to rows. Columns can contain plan text, form elements(input, select, checkbox), or html tags(span, div). Consider the following 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>

after dom operation i need the following:

<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();

its working fine, but its adding empty rows:

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

Any idea whats am i doing wrong??

You can parse HTML and XML with DOM, this is how you could read a table:

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

To print the structure flattened:

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

You can move each <td> element into a new <tr> child of it's current ancestor <table> element:

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

Afterwards you can remove all <tr> elements that do not have any <td> children any longer:

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

Your document has now been transformed:

<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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM