Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP-code blocks in templates loaded in DOMDocument

I need to parse HTML-template with DOMDocument. But HTML code may contain PHP-code blocks, for example:

<div id="test" data="<?php echo $somevar?>"> </div>

When I load this HTML I get error "Unescaped '<' not allowed in attributes values...". Parser thinks that attribute "data" has no closing quote and <php is new tag. How can I specify to ignore <php tag or something like that?

like image 709
WindBridges Avatar asked Mar 06 '26 00:03

WindBridges


1 Answers

Your HTML code:

<div id="test" data="<?php echo $somevar?>"> </div>

Is not XML code. For XML it's invalid, HTML is okay. To load HTML code with DOMDocument, you can use the DOMDocument::loadHTML­Docs function.

It will load your template without any error.

Example / Demo:

$html = '<div id="test" data="<?php echo $somevar?>"> </div>';
$doc = new DOMDocument();
$doc->loadHTML($html);

Related: Can PHP include work for only a specified portion of a file?

like image 161
hakre Avatar answered Mar 09 '26 11:03

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!