Agantacroxi
Agantacroxi

Reputation: 81

How can I prevent PHP to HTML encode tags in saveHTMLFile?

I have a small problem: the tags, e.g. <br> tags, are not parsed when submitting a PHP DomDocument. Here is my PHP code:

$doc = new DOMDocument();
$doc->loadHTMLFile("Test.html");
$doc->formatOutput = true;
$node = new DOMElement('p', 'This is a test<br>This should be a new line in the same paragraph');
$doc->getElementsByTagName('body')->item(0)->appendChild($node);
$doc->saveHTMLFile("Test.html");
echo 'Editing successful.';

Here is the HTML code (before editing):

<!DOCTYPE html>
<html>
    <head>
        <title>Hey</title>
    </head>
    <body>
        <p>Test</p>   
    </body>
</html>

(after editing)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hey</title>
</head>
<body>
    <p>Test</p>   
<p>This is a test&lt;br&gt;This should be a new line in the same paragraph</p>
</body>
</html>

Why is it not working?

Upvotes: 0

Views: 651

Answers (2)

Wrikken
Wrikken

Reputation: 70460

You are trying to append a fragment, which does not work as 'normal' string (how ever would it know what you want it to encode and what not?).

You can use theDOMDocumentFragment::appendXML() function, but as the name states, it wants XML, not HTML, so for this the <br> needs to be self-closing (because we are working in XML mode):

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("Test.html");
$doc->formatOutput = true;
$node = new DOMElement('p');
$p =  $doc->lastChild->lastChild->appendChild($node);
$fragment = $doc->createDocumentFragment();
$fragment->appendXML('This is a test<br/>This should be a new line in the same paragraph');
$p->appendChild($fragment);
$doc->saveHTMLFile("Test.html");

Another solution not involving altering your string is to load a seperate document as HTML (so, $otherdoc->loadHTML('<html><body>'.$yourstring.'</body></html>'), and then loop through it importing in the main doc:

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("Test.html");
$doc->formatOutput = true;
$node = new DOMElement('p');
$p =  $doc->lastChild->lastChild->appendChild($node);
$otherdoc = new DOMDocument();
$yourstring = 'This is a test<br>This should be a new line in the same paragraph';
$otherdoc->loadHTML('<html><body>'.$yourstring.'</body></html>');
foreach($otherdoc->lastChild->lastChild->childNodes as $node){
    $importednode = $doc->importNode($node);
    $p->appendChild($importednode);
}
$doc->saveHTMLFile("Test.html");

Upvotes: 2

Kavi Siegel
Kavi Siegel

Reputation: 2994

Have you tried <br/> rather than <br>? It could have to do with validity of the markup. <br> is invalid.

Upvotes: 0

Related Questions