2

I want to append my head tag with script tag(with some contents) in external Html file using PHP code. But my Html is not updating or showing any errors.

PHP Code:

<?php

$doc = new DOMDocument();
$doc->loadHtmlFile( 'myfolder/myIndex.html');
$headNode = $doc->getElementsByTagName('head')->item(0);

$scriptNode = $doc->createElement("script");
$headNode->appendChild($scriptNode);

echo $doc->saveXML();

?>

Html File :

(A simple html pattern)

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

I have refered to the documentation here Couldn't figure out the problem still.

6
  • What did the echo statement show? Commented Sep 30, 2019 at 7:39
  • Works fine 3v4l.org/AQOau Commented Sep 30, 2019 at 7:40
  • Are you perhaps under the impression that $doc->saveXML() would change the HTML file on the disk that you initially read the HTML code from …? Commented Sep 30, 2019 at 7:47
  • @KoalaYeung showing nothing. Commented Sep 30, 2019 at 8:29
  • 2
    php.net/manual/en/domdocument.savehtmlfile.php Commented Sep 30, 2019 at 8:32

1 Answer 1

1

Given a very simple HTML file ( simple.html )

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>A simple HTML Page</title>
    </head>
    <body>
        <h1>Simple HTML</h1>
        <p>Well this is nice!</p>
    </body>
</html>

Then using the following

$file='simple.html';


libxml_use_internal_errors( true );
$dom=new DOMDocument;
$dom->validateOnParse=false;
$dom->recover=true;
$dom->strictErrorChecking=false;
$dom->loadHTMLFile( $file );
$errors = libxml_get_errors();
libxml_clear_errors();




$script=$dom->createElement('script');
$script->textContent='/* Hello World */';

/* use [] notation rather than ->item(0) */
$dom->getElementsByTagName('head')[0]->appendChild( $script );



printf('<pre>%s</pre>',htmlentities( $dom->saveHTML() ));

/* write changes back to the html file - ie: save */
$dom->saveHTMLFile( $file );

will yield ( for display )

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>A simple HTML Page</title>
    <script></script></head>
    <body>
        <h1>Simple HTML</h1>
        <p>Well this is nice!</p>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

3 Comments

printf displaying html fine, but html file is not updating similarly
at the end you need to save the file once more.. I'll edit the answer
Good - glad it helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.