如何在同一 table 行中合并两个 table 单元格?

How to combine two table cells in the same table row?

如何将 date td/cell 合并到 time td/cell 中?

我希望 table 行包含 3 个单元格,中间的单元格应显示为 date time

我的代码:

$dom = new DOMDocument;
$dom->loadHTMLFile("test.html");
$dom->validateOnParse = true;
$xpath                = new DOMXPath($dom);
$table = $xpath->query("//*[@class='mytable']//tbody")->item(0);
$td = $table->getElementsbytagname("td");

test.html 文件内容:

<table class="mytable">
  <tbody><tr>
      <td>date</td>
      <td>td1</td>
      <td>time</td>
      <td>td2</td>
    </tr></tbody>
</table>

想要的结果:

<table class="mytable">
  <tbody><tr>
      <td>td1</td>
      <td>date time</td>
      <td>td2</td>
    </tr></tbody>
</table>

收集tbody tr细胞。使用第一个出现的单元格的文本覆盖第三个出现的单元格的文本,然后删除第一个单元格。

代码 (Demo)

$html = <<<HTML
<table class="mytable">
  <tbody><tr>
      <td>date</td>
      <td>td1</td>
      <td>time</td>
      <td>td2</td>
    </tr></tbody>
</table>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//table[@class='mytable']/tbody/tr") as $tr) {
    $tds = $tr->getElementsByTagName("td");
    $tds->item(2)->nodeValue = $tds->item(0)->nodeValue .
                               ' ' . $tds->item(2)->nodeValue;
    $tr->removeChild($tds->item(0));
}
echo $dom->saveHTML();

输出:

<table class="mytable">
  <tbody><tr>

      <td>td1</td>
      <td>date time</td>
      <td>td2</td>
    </tr></tbody>
</table>