php - 如何使用 php 将 html 标记写入另一个 html 文件?

标签 php html writefile

我有两个文件。一个是 input.php,另一个是 output.html。
内部 input.php 文件的代码如下:

<?php

   $file="output.html";
   $doc=new DOMDocument('1.0');
   $doc->loadHTMLFile($file);
   $elements = $doc->getElementsByTagName('head');

   $jscript=$doc->createElement("script");
   $jstype=$doc->createAttribute("type");
   $jstText=$doc->createTextNode("text/javascript");
   $jstype->appendChild($jstText);
   $jscript->appendChild($jstype);
   $jssource=$doc->createAttribute("src");
   $jssText=$doc->createTextNode("xxxxx.js");
   $jssource->appendChild($jssText);
   $jscript->appendChild($jssource);
   $elements->item(0)->appendChild($jscript);
   $doc->save("output.html");   
?>

在 output.html 文件中:

<code>   
 <html>
   <head>
   </head>
   <body>
   </body>
 </html>
</code>

实际上,我想添加 output.html 下的“head”。但是现在有两个问题。

1.虽然可以在output.php文件中写入内容,但总是排在文件的第一行,导致html页面无法正常工作。

2.标签始终添加为 . (xml 格式)。它不起作用,我需要(html 格式)

这2个问题有解决办法吗?或者还有其他方法可以实现我的目标吗? (在 input.php 文件中我尝试了 saveHTML() - 还是不行)

最佳答案

来自文档

DOMDocument::save — Dumps the internal XML tree back into a file

难怪您会得到 XML 表示。您应该按照评论中的建议尝试 DOMDocument::saveHTMLFile 或者您可以尝试 echo $doc->saveHTML();

关于php - 如何使用 php 将 html 标记写入另一个 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11977873/

相关文章:

php - magic-quotes 是 ON && 一起使用 stripslashes 和 mysql-real-escape-string

c - 将函数及其大小传递给 WriteFile

c - 使用 Windows 套接字的 WriteFile 返回无效参数错误

php - 关于 mysql 时间戳数据类型的提示

php - 如何对数组元素进行分组?

php - python 中最接近 WordPress 而不是 php 的东西是什么?

jQuery从div中获取数据

jquery - fancyBox - YouTube 视频不会显示

javascript - 滚动时制作页面内容封面和图像

c++ - 无法在 C++ 中写入文件