好的,这是我的html内容:
<p> .... </p>
<div id="quick_preview">
<p>the contents </p>
</div>
我想要的是:
<p> .... </p>
<div id="quick_preview">
<description>
<p>the contents </p>
</description>
</div>
我使用此例程查找div
并创建description
代码,但我不知道如何在<description>
之前将p
插入div:
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($row['body']);
$divs = $dom->getElementsByTagName('div');
foreach($divs as $div)
{
if ($div->getAttribute( "id" ) == 'quick_preview') {
$desc_element = $dom->createElement('description');
}
}
$dom->saveHTMLFile($html)
答案 0 :(得分:2)
这将做你想要的:
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($row['body']);
$xpath = new DOMXPath($dom);
$divs = $xpath->query('//div[@id="quick_preview"]');
foreach ($divs as $div)
{
$description = $dom->createElement('description');
while ( $div->hasChildNodes() )
{
$description->appendChild($div->firstChild);
}
$div->appendChild($description);
}
$dom->saveHTMLFile($html);
您可以删除XPath并改为使用$dom->getElementById('quick_preview')
。
请注意,您只需将文档附加到文档中的其他位置即可移动DOM节点。
答案 1 :(得分:1)
答案:
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($row['body']);
$ps = $dom->getElementsByTagName('p');
$xpath = new DOMXPath($dom);
foreach($ps as $p)
{
if ($p->parentNode->getAttribute( "id" ) == 'quick_preview') {
$desc_element = $dom->createElement('description');
$desc_element->appendChild($p);
$divs = $xpath->query('//div[@id="quick_preview"]');
foreach($divs as $div){
$div->appendChild($desc_element);
}
}
}
echo $dom->saveHTML();