dongxieli3839 2013-09-26 12:15
浏览 25
已采纳

如何将简单的html(从其他文件)附加到PHP中的HTML DOM元素?

I have the main document created with DOM server-side using PHP. And I have to include some pieces of PHP/HTML without DOM. Example. There is file form.php containing a form

<form action="" method="post"> 
  <input type="text" name="firstname" id="firstnameid" /><br/>
  <input type="submit" name="submit" value="Submit" />
</form>

I want to place that form into a <DIV> created using DOM in the file index.php. The DIV inside depends on other logic (condition $form_is_needed)

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="utf-8" /> </head>

<body>
<?php
$form_is_needed = true;
$dom = new DOMDocument();
$domDiv = $dom->createElement("div"); 

if ($form_is_needed) {
  // trying load not DOM
  $str = file_get_contents('form.php');
  $domDivText = $dom->createTextNode( html_entity_decode( $str )  );
  $domDiv->appendChild($domDivText);
}
else {
  $domDivText = $dom->createTextNode( "There is no form." );
  $domDiv->appendChild($domDivText);
}

$dom->appendChild($domDiv);
$html = $dom->saveHTML();
echo $html; 
?>
</body>
</html>

I get my content inside DIV but the escape characters has been added

<div>&lt;form action="" method="post"&gt; 
  &lt;input type="text" name="firstname" id="firstnameid" /&gt;&lt;br/&gt;
  &lt;input type="submit" name="submit" value="Submit" /&gt;
&lt;/form&gt;
</div>
  • 写回答

2条回答 默认 最新

  • dongmaobeng7145 2013-09-26 12:23
    关注

    There is, to my knowledge, no node which can emit raw content, but if it is well-formed, you could try loading it into a DOMDocumentFragment and appending it that way:

    $frag = $dom->createDocumentFragment();
    $frag->appendXML($str);
    $domDiv->appendChild($frag);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?