2012-08-15 38 views
3

我有兩個文件。一個是input.php,另一個是output.html。
內input.php文件中的代碼如下:如何使用php將html標籤寫入另一個html文件?

<?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()方法 - 還是不行)

+0

你嘗試'saveHTMLFile()'? – Musa 2012-08-15 22:02:27

+0

謝謝,它的工作原理。 – 2012-08-16 00:09:32

回答

3

從文檔

的DOMDocument ::保存 - 轉儲內部XML樹迴文件

所以你難怪你會得到一個XML表示。你應該嘗試DOMDocument::saveHTMLFile作爲已經在評論中建議,或者你可以嘗試echo $doc->saveHTML();

+0

感謝,現在工作得很好。 – 2012-08-16 00:09:56

相關問題