3

我有两个文件。一个是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 的“头”。但是现在有两个问题。

1.虽然内容可以写在output.php文件中,但总是在文件的第一行,导致html页面打不开。

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

有没有解决这2个问题的方法?或者有没有其他方法可以实现我的目标?(在 input.php 文件中我尝试了 saveHTML() - 仍然不起作用)

4

1 回答 1

3

从文档

DOMDocument::save — 将内部 XML 树转储回文件中

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

于 2012-08-15T22:12:44.113 回答