<?php
$html = <<<HTML
<html>
	<head>
	</head>
	<body>
		<script>
			$('h1').addClass('header');
		</script>
		<h1>DOMDocument</h1>
		<p>Text<p>
		<script src="jquery.js"></script>
		
		<!-- inline php should appear below -->
	</body>
</html>
HTML;

echo move_script($html);

function move_script($html)
{
	$dom = new DOMDocument();
	$dom->recover = true;
	//$dom->substituteEntities = true;
	$dom->formatOutput = true;
	$dom->preserveWhiteSpace = false;
	
	// set error level
	//$internalErrors = libxml_use_internal_errors(true);
	$dom->loadHTML($html);
	// Restore error level
	//libxml_use_internal_errors($internalErrors);

	$xpath = new DOMXPath($dom);
	// grab the inline scripts.
	$script_tags = $xpath->query('//body//script[not(@src)]');

	$mainBody = @$dom->getElementsByTagName('body')->item(0);
	foreach ($script_tags as $tag) {
	    $mainBody->appendChild($tag->cloneNode(true));
	    $tag->parentNode->removeChild($tag);
	}

	return $dom->saveHTML();
}
