// Start output buffering with a callback function to inject the JavaScript ob_start(function($buffer) { // Define the script tag to be injected $script = ''; // Inject the JavaScript before the closing body tag, if it exists return preg_replace("##", "$script\n", $buffer, 1); }); /