fork download
  1. <?php
  2. $html = <<<HTML
  3. <html>
  4. <head>
  5. </head>
  6. <body>
  7. <script>
  8. $('h1').addClass('header');
  9. </script>
  10. <h1>DOMDocument</h1>
  11. <p>Text<p>
  12. <script src="jquery.js"></script>
  13.  
  14. <!-- inline php should appear below -->
  15. </body>
  16. </html>
  17. HTML;
  18.  
  19. echo move_script($html);
  20.  
  21. function move_script($html)
  22. {
  23. $dom = new DOMDocument();
  24. $dom->recover = true;
  25. //$dom->substituteEntities = true;
  26. $dom->formatOutput = true;
  27. $dom->preserveWhiteSpace = false;
  28.  
  29. // set error level
  30. //$internalErrors = libxml_use_internal_errors(true);
  31. $dom->loadHTML($html);
  32. // Restore error level
  33. //libxml_use_internal_errors($internalErrors);
  34.  
  35. $xpath = new DOMXPath($dom);
  36. // grab the inline scripts.
  37. $script_tags = $xpath->query('//body//script[not(@src)]');
  38.  
  39. $mainBody = @$dom->getElementsByTagName('body')->item(0);
  40. foreach ($script_tags as $tag) {
  41. $mainBody->appendChild($tag->cloneNode(true));
  42. $tag->parentNode->removeChild($tag);
  43. }
  44.  
  45. return $dom->saveHTML();
  46. }
  47.  
Success #stdin #stdout 0.01s 52488KB
stdin
Standard input is empty
stdout
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://w...content-available-to-author-only...3.org/TR/REC-html40/loose.dtd">
<html>
<head></head>
<body>
		<h1>DOMDocument</h1>
		<p>Text</p>
<p>
		<script src="jquery.js"></script><!-- inline php should appear below --></p>
<script>
			$('h1').addClass('header');
		</script>
</body>
</html>