我有两个文件。一个是 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/