note 126480 deleted from domdocument.loadhtml by cmb
| From: | cmb@php.net | Date: | Wed, 06 Oct 2021 07:56:50 +0000 |
| Subject: | note 126480 deleted from domdocument.loadhtml by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217037@lists.php.net to get a copy of this message | ||
Note Submitter: ar_miriel at yahoo dot de
----
If you use a template in which you pass a variable from php to Javascript and embed the template
via loadHTMLFile, you may experience difficulties.
In the following example template.php is interpreted just fine on its own, but when embedded in the
index.php it throws the syntaxError unexpected token '<' and the ReferenceError that
par is not defined in the onload statement.
template.php:
_______________
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript">
var testvar=<?php echo "'blub'"; ?>
var par =document.createElement("p");
var text=document.createTextNode(testvar);
par.append(text);
</script>
</head>
<body onload="document.body.append(par);">
can you see a blub after this text:
<noscript> probably not</noscript>
</body>
</html>
_______________
index.php:
_______________
$dom=new DOMDocument('1.0','utf-8');
libxml_use_internal_errors(true);
$dom->loadHTMLFile("template.php");
echo $dom->saveHTML();
flush();
ob_flush();
_______________
This needs to be a part of the Docu since you want to know this in the beginning when you structure
the project because yoe can actually work around this:
The workaround for this problem is to not transfer the variable testvar from php to javascript in
the template but in the index.php:
template.php:
_______________
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head>
<body onload="document.body.append(par);">
can you see a blub after this text:
<noscript> probably not</noscript>
</body>
</html>
_______________
index.php:
_______________
$dom=new DOMDocument('1.0','utf-8');
libxml_use_internal_errors(true);
$dom->loadHTMLFile("template.php");
//new:
$testvar="blub";
$js=$dom->createTextNode('script');
$js->setAttribute('type','text/javascript');
$text=$dom->createTextNode('
var testvar= "'.blub.'";
var par =document.createElement("p");
var text=document.createTextNode(testvar);
par.append(text);');
$js->appendChild($text);
$dom->getElementsByTagName('head')[0]->appendChild($js);
echo $dom->saveHTML();
flush();
ob_flush();
_______________