用 dom PHP 创建的不需要的 div



可以在不显示 xml 标签且没有任何问题的情况下创建主div

$myfile = fopen("../userfolders/$email/$ongrassdb/$pagenameselected.php", "a+") or die("Unable to open file!");
$dom = new DOMDocument();
$ele = $dom->createElement('div', $textcon);
$ele ->setAttribute('id', $divname);
$ele ->setAttribute('style', 'background: '.$divbgcolor.'; color :'.$divfontcolor.' ;display : table-col; width :100%;');
$dom->appendChild($ele);
$html = $dom->saveHTML();
fwrite($myfile,$html);
fclose($myfile);
尝试创建子div,

但下面的代码创建父div 和子div 的副本,并在每个div 后添加 XML 标记

$myfile = fopen("../userfolders/$email/$ongrassdb/$pagenameselected.php", "a+") or die("Unable to open file!");
$file = "../userfolders/$email/$ongrassdb/$pagenameselected.php";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$ele = $doc->createElement('div', $textcon);
$element = $doc->getElementsByTagName('div')->item(0);
$element->appendChild($ele);
$ele ->setAttribute('id', $divname);
$ele ->setAttribute('style', 'background: '.$divbgcolor.'; color :'.$divfontcolor.' ;display : table-cell;');
$doc->appendChild($ele);
$html = $doc->saveHTML();
fwrite($myfile,$html);

更新

这个怎么样

您将有三个文件,$outputfile将是保存 html 的新文件。 $parentfile和$childfile是您要从中提取div的两个文件。 $pId 是父div 的 ID,$cId是子div 的 ID(如果我没有记错的话,应该在创建文件时设置)

$outputfile = '/path/to/new/output/file/';
$parentfile = '/path/to/file/with/parent/div/';
$childfile = '/path/to/file/with/child/div/';
$pId = 'myParentDivId';
$cId = 'myChildDivId';
$file = $parentfile;
$p = new DOMDocument();
$p->loadHTMLFile($file);
$pEle = $p->getElementById($pId);
$file = $childfile;
$c = new DOMDocument();
$c->loadHTMLFile($file);
$cEle = $c->getElementById($cId);
$pEle->appendChild($cEle);
$m = new DOMDocument();
$m->appendChild($pEle);
$myfile = fopen($outputfile, "a+") or die('bye');
$html = $m->saveHTML();
fwrite($myfile,$html);
fclose($myfile);

这是一个模板,用于随意创建父节点并附加子节点。

<?php
    $oDom                     = new DOMDocument( '1.0', 'UTF-8' );
    $oDom->preserveWhiteSpace = false;
    $oDom->formatOutput       = true;
    $iErrorFlag               = true;
    libxml_use_internal_errors( true );
    $oLog = $oDom->createElement( 'log' );
    $oDom->appendChild( $oLog );
    $oNde = $oDom->createElement( 'lognode' );
    $oLog->appendChild( $oNde );
    $oNde->appendChild( $oDom->createElement( 'message', 'My message!' ) );
    $oNde->appendChild( $oDom->createElement( 'user'   , 'My user!'    ) );
    $oNde->appendChild( $oDom->createElement( 'ip'     , 'My ip!'      ) );
    $bSuccess = file_put_contents( 'logfile.xml', $oDom->saveXML() );
?>

将 a+ 更改为 w+,同时将 saveXML 更改为 saveHTML

它将解决问题

谢谢

最新更新