|
If you're writing a Joomla module you may notice that $mainframe->addCustomHeadTag() does not work. The reason is that the <HEAD> section of the HTML document has already been outputted by PHP. Here's the work around...
Inject Head Tags
function injectCustomHeadTags($html) {
$buf = ob_get_contents();
ob_clean();
$buf = preg_replace("/<head(.*?)>(.*?)<\/head>/is", "<head$1>$2".$html."</head>", $buf);
echo $buf;
}
All you have to do is include that function in your module, and then call it with the HTML you want injected into the HEAD section of your HTML Document as the parameter.
Update
This modification of the function will return true of false if the insertion into the HEAD section succeeds or not. This is useful since the output buffering can be limited to a number of bytes, and the body may exceed this, or the buffer may have been flushed prematurely.
function injectCustomHeadTags($html) {
$buf = ob_get_contents();
if (!empty($buf) && !headers_sent()) {
$buf = preg_replace("/<head(| .*?)>(.*?)<\/head>/is", "<head$1>$2".$html."</head>", $buf, 1, $count);
if ($count == 1) {
ob_clean();
echo $buf;
return true;
}
}
return false;
}
Example Usage:
if (!injectCustomHeadTags($html)) {
echo $html;
}
This will only work however if your PHP Server supports HTTP output buffering. Fortunately, this will work for most Joomla sites. Actually, it works a custom PHP page as well.
How it works
Joomla fortunately has output buffering started by default. This allows us to access the HTTP output buffer from any Joomla extension. It does this by calling ob_start() at the beginning of the Joomla index.php page.
$buf = ob_get_contents();
ob_get_contents() returns everything buffered by PHP from echo(), print(), even plain HTML. We save this buffered output to $buf.
ob_clean();
Will clear the buffer. Thus the next call to ob_get_contents() would return an empty string.
$buf = preg_replace("/<head(.*?)>(.*?)<\/head>/is", "<head$1>$2".$html."</head>", $buf);
Here we modify the HTML string we have in $buf. preg_replace() takes a pattern (regular expression) and matches the pattern inside the string $buf. If it finds the pattern, it will replace it with the replacement string. We've used to to replace the HEAD section with a new HEAD section containing our new head tags.
echo $buf;
Here we echo the modified buffer. This will insert it back into the buffer, with your custom HEAD tags in the HEAD section.
Discussions on this topic
http://forum.joomla.org/index.php/topic,92494.0.html
|