function _ai_injectXPath in Content Injector (formerly AdSense Injector) 6.3
Same name and namespace in other branches
- 7.3 adsense_injector.module \_ai_injectXPath()
Inject an HTML fragment into the node body, using XPath expression.
@todo Fix entity encoding problem! http://www.php.net/manual/en/domdocument.loadhtml.php#95251 http://devzone.zend.com/article/8855
Parameters
$body The node body to operate on.:
$fragment The HTML fragment to inject.:
$xpath_expression The XPath expression to use:
$encoding The character encoding to use. Defaults to 'UTF-8'.:
1 call to _ai_injectXPath()
- adsense_injector_process_body in ./
adsense_injector.module - Process the body, handle adsense injector tags. Look for an insertion point based on paragraphs.
File
- ./
adsense_injector.module, line 254 - Inject adsense ads into node content automatically.
Code
function _ai_injectXPath($body, $fragment, $xpath_expression, $encoding = 'UTF-8') {
try {
$doc = new DomDocument();
// HACK: Fix entity encoding http://www.php.net/manual/en/domdocument.loadhtml.php#95251 et al.
$encoding_string = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset={$encoding}\">";
$prehtml = "<html><head>{$encoding_string}</head><body>";
$posthtml = "</body></html>";
@$doc
->loadHTML($prehtml . $body . $posthtml);
$xpath = new DOMXpath($doc);
$ent = $xpath
->query($xpath_expression);
if (!empty($ent) && $ent->length > 0) {
// http://stackoverflow.com/questions/2255158/how-do-i-insert-html-into-a-php-dom-object
$frag = $doc
->createDocumentFragment();
$frag
->appendXML($fragment);
$ent
->item(0)
->appendChild($frag);
// DOMDocument->saveHTML() doesn't accept a child element unless in PHP
// 5.3.6 or above. So we'll have to do this the ugly way (as described
// in http://php.net/manual/en/domdocument.savehtml.php#85165
// $html_fragment = $doc->saveHTML($doc->getElementsByTagName('body')->item(0));
//
// If needed, we can do a manual encoding fixup
// $doc = _ai_fixup_html_encoding($doc);
$html_fragment = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace(array(
$encoding_string,
'<html>',
'</html>',
'<head>',
'</head>',
'<body>',
'</body>',
), '', $doc
->saveHTML()));
}
else {
$html_fragment = $body . _ai_html_comment('injectXPath', "XPath query '{$xpath_expression}' result empty; insertion skipped ");
}
} catch (Exception $e) {
$html_fragment = $body . _ai_html_comment('injectXPath error', $e
->getMessage());
}
return $html_fragment;
}