合并两个DOMDocument节点
问题描述:
<table>
<tr>
<th>Year</th>
<th>Score</th>
</tr>
<tr>
<td>2014</td>
<td>3078</td>
</tr>
</table>
如果我把上面的表成功存储为一个变量,我怎么能将它附加到具有overflow-x样式属性的div?合并两个DOMDocument节点
我试过下面的代码片段,但没有雪茄:
$div = str_get_html('<div style="overflow-x:auto;"></div>');
$div = $div->find('div');
$div = $div->appendChild($table);
return $div;
所以预期输出应该是:
<div style="overflow-x:auto;">
<table>
<tr>
<th>Year</th>
<th>Score</th>
</tr>
<tr>
<td>2014</td>
<td>3078</td>
</tr>
</table>
</div>
答
希望这一个会给你实施的基本思路。这里我们使用的是DOMDocument
。
<?php
ini_set('display_errors', 1);
//creating table node
$tableNode='<table><tr><th>Year</th><th>Score</th></tr><tr><td>2014</td><td>3078</td></tr></table>';
$domDocument = new DOMDocument();
$domDocument->encoding="UTF-8";
$domDocument->loadHTML($tableNode);
$domXPath = new DOMXPath($domDocument);
$table = $domXPath->query("//table")->item(0);
//creating empty div node.
$domDocument = new DOMDocument();
$element=$domDocument->createElement("div");
$element->setAttribute("style", "overflow-x:auto;");
$result=$domDocument->importNode($table,true);//importing node from of other DOMDocument
$element->appendChild($result);
echo $domDocument->saveHTML($element);
你没有张贴同样的问题早? – Barmar
@ D.Wells你能分享你的预期产出吗? –
@Sahil我已经将它添加到现在的问题 –