PHP DomDocument,将页面元素附加到另一个页面

时间:2013-07-11 08:48:06

标签: php domdocument

我有一个用于生成商店的PHP脚本。

所以,首先我用dom文件检索我的html页面:

$oPage = new webHTML("boutique_panier_HTML");
$oInter = $oPage->getElementById("inter");

webHTML()只是一个自定义的DomDocument类。所以,我检索我的主要div(inter),然后在return $oPage->saveHTML();

之前对这个div做一些处理

所以,现在,没关系。

我需要加载另一个页面,检索一个元素(表单)并将此元素放在我的$oInter上。

所以,在return $oPage->saveHTML();之前juste,我这样做:

$oPage2 = new webHTML("formulaire_bon_commande");
$oInter2 = $oPage2->getElementsByTagName("form");
$oInter->appendChild($oInter2);

所以,我加载页面“formulaire_bon_commande”,我检索我的元素表单,并尝试将此元素追加到我的$ oInter div。

使用此代码,我只有一个白页......没有效果。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

方法getElementsByTagName返回DOMNodeListappendChild需要DOMNode,因此您必须迭代$oInter2

$oInter2 = $oPage2->getElementsByTagName("form");
foreach ($oInter2 as $el){
   $node = $oPage->importNode($el, true);
   $oInter->appendChild($node);
}

示例:

$oPage = new DOMDocument();
$oPage->loadHTML('<html><p id="inter"></p></html>');
$oInter = $oPage->getElementById("inter");


$oPage2 = new DOMDocument();
$oPage2->loadHTML('<html><form><button></button></form></html>');
$oInter2 = $oPage2->getElementsByTagName("form");
foreach($oInter2 as $el) {
    $node = $oPage->importNode($el, true);
    $oInter->appendChild($node);
}

echo $oPage->saveHTML();

输出:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p id="inter"><form><button></button></form></p></body></html>