I'm developing a Joomla system plugin. I need to add javascript and css files if the certain [myshortcode] shortcode found in content.
How can I get the content in onBeforeCompileHead function
function onBeforeCompileHead() {
$document = JFactory::getDocument();
//add scripts only if shortcode found
...
$document->addStyleSheet($cssFile, 'text/css', null, array());
The $content = JResponse::getBody(); does not work.
Thanks
Try this,
For style sheet,
$document = JFactory::getDocument();
$document->addStyleSheet('http://domain.com/templates/css/style.css');
For Javascript File
$document = JFactory::getDocument();
$document->addScript('full url');
Also you can do like this,
$document = JFactory::getDocument();
// Add Javascript
$document->addScriptDeclaration('
window.event("domready", function() {
alert("An inline JavaScript Declaration");
});
');
// Add styles
$style = 'body {'
. 'background: #00ff00;'
. 'color: rgb(0,0,255);'
. '}';
$document->addStyleDeclaration($style);
If this case any jQuery issue you can try addCustomTag option too like here
Hope its helps..
Related
I'm looking to turn
Some page to
Some page
using PHP. I'll have the HTML code of a random website so it's not as simple as using str_replace()
I've tried Replacing anchor href value with regex but that seems to just erase my entire page and I get a blank, white screen. Can anyone offer any help?
My code:
$html = file_get_contents(htmlentities($_GET['q'])); // Takes contents of website entered by user
$arr = array(); // Defines array
$html2 = ""; // Defines variable to write to later
$dom = new DOMDocument();
$dom->loadHTML($html); // Loads the HTML code displayed earlier
$domcss = $dom->getElementsByTagName('link');
foreach($domcss as $links) {
if( strtolower($links->getAttribute('rel')) == "stylesheet" ) {
$x = $links->getAttribute('href');
$html2 .= '<link rel="stylesheet" type="text/css" href="'.htmlentities($_GET['q']) . "/" . $x.'">';
}
} // This replaces all stylesheets from "./style.css", to "http://example.com/style.css"
echo $html2 . $html // Echos the entire webpage, with stylesheet links edited
To manipulate this with DOM, find the <a> tags and then if there is a href attribute, add the prefix in. The end of this code just echos out the resultant HTML...
$dom = new DOMDocument();
$dom->loadHTML($html); // Loads the HTML code displayed earlier
$aTags = $dom->getElementsByTagName('a');
$prefix = "http://example.com?q=";
foreach($aTags as $links) {
$href = $links->getAttribute('href');
if( !empty($href)) {
$links->setAttribute("href", $prefix.$href);
}
}
echo $dom->saveHTML();
$prefix contains the bit you want to add the the URL.
I have been working with this php code, which should modify Google Calendars layout. But when I put the code to page, it makes everything below it disappear. What's wrong with it?
<?php
$your_google_calendar=" PAGE ";
$url= parse_url($your_google_calendar);
$google_domain = $url['scheme'].'://'.$url['host'].dirname($url['path']).'/';
// Load and parse Google's raw calendar
$dom = new DOMDocument;
$dom->loadHTMLfile($your_google_calendar);
// Change Google's CSS file to use absolute URLs (assumes there's only one element)
$css = $dom->getElementByTagName('link')->item(0);
$css_href = $css->getAttributes('href');
$css->setAttributes('href', $google_domain . $css_href);
// Change Google's JS file to use absolute URLs
$scripts = $dom->getElementByTagName('script')->item(0);
foreach ($scripts as $script) {
$js_src = $script->getAttributes('src');
if ($js_src) { $script->setAttributes('src', $google_domain . $js_src); }
}
// Create a link to a new CSS file called custom_calendar.css
$element = $dom->createElement('link');
$element->setAttribute('type', 'text/css');
$element->setAttribute('rel', 'stylesheet');
$element->setAttribute('href', 'custom_calendar.css');
// Append this link at the end of the element
$head = $dom->getElementByTagName('head')->item(0);
$head->appendChild($element);
// Export the HTML
echo $dom->saveHTML();
?>
When I'm testing your code, I'm getting some errors because of wrong method call:
->getElementByTagName should be ->getElementsByTagName with s on Element
and
->setAttributes and ->getAttributes should be ->setAttribute and ->getAttribute without s at end.
I'm guessing that you don't have any error_reporting on, and because of that don't know anything went wrong?
I want to rewrite/mask all external url in my article and also add nofollow and target="_blank". So that original link to the external site is get encrypted/ masked/ rewritten.
For example:
original link: www.google.com
rewrite it to: www.mydomain.com?goto=google.com
There is a plugin for joomla which rewrite external link: rewrite plugin.
But I am not using joomla. Please have a look at above plugin, It does exactly what I am looking for.
What I want?
$article = "hello this is example article I want to replace all external link http://google.com";
$host = substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.' ? substr($_SERVER['HTTP_HOST'], 0) : $_SERVER['HTTP_HOST'];
if (thisIsNotMyWebsite){
replace external url
}
You can use DOMDocument to parse and traverse the document.
function rewriteExternal($html) {
// The url for your redirection script
$prefix = 'http://www.example.com?goto=';
// a regular expression to determine if
// this link is within your site, edit for your
// domain or other needs
$is_internal = '/(?:^\/|^\.\.\/)|example\.com/';
$dom = new DOMDocument();
// Parse the HTML into a DOM
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
if (!preg_match($is_internal, $href)) {
$link->getAttributeNode('href')->value = $prefix . $href;
$link->setAttributeNode(new DOMAttr('rel', 'nofollow'));
$link->setAttributeNode(new DOMAttr('target', '_blank'));
}
}
// returns the updated HTML or false if there was an error
return $dom->saveHTML();
}
This approach will be much more reliable than using a regular expression based solution since it actually parses the DOM for you instead of relying on a often-fragile regex.
something like:
<?php
$html ='1224 google 567';
$tracking_string = 'http://example.com/track.php?url=';
$html = preg_replace('#(<a[^>]+href=")(http|https)([^>" ]+)("?[^>]*>)#is','\\1'.$tracking_string.'\\2\\3\\4',$html);
echo $html;
in action here: http://codepad.viper-7.com/7BYkoc
--my last update
<?php
$html =' 1224 google 567';
$tracking_string = 'http://example.com/track.php?url=';
$html = preg_replace('#(<a[^>]+)(href=")(http|https)([^>" ]+)("?[^>]*>)#is','\\1 nofollow target="_blank" \\2'.$tracking_string.'\\3\\4\\5',$html);
echo $html;
http://codepad.viper-7.com/JP8sUk
I have this function to get title of a website:
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
However, this function make my page took too much time to response. Someone tell me to get title by request header of the website only, which won't read the whole file, but I don't know how. Can anyone please tell me which code and function i should use to do this? Thank you very much.
Using regex is not a good idea for HTML, use the DOM Parser instead
$html = new simple_html_dom();
$html->load_file('****'); //put url or filename
$title = $html->find('title');
echo $title->plaintext;
or
// Create DOM from URL or file
$html = file_get_html('*****');
// Find all images
foreach($html->find('title') as $element)
echo $element->src . '<br>';
Good read
RegEx match open tags except XHTML self-contained tags
Use jQuery Instead to get Title of your page
$(document).ready(function() {
alert($("title").text());
});
Demo : http://jsfiddle.net/WQNT8/1/
try this will work surely
include_once 'simple_html_dom.php';
$oHtml = str_get_html($url);
$Title = array_shift($oHtml->find('title'))->innertext;
$Description = array_shift($oHtml->find("meta[name='description']"))->content;
$keywords = array_shift($oHtml->find("meta[name='keywords']"))->content;
echo $title;
echo $Description;
echo $keywords;
I am looking for suitable replacement code that allows me replace the content inside of any HTML tag that has a certain class e.g.
$class = "blah";
$content = "new content";
$html = '<div class="blah">hello world</div>';
// code to replace, $html now looks like:
// <div class="blah">new content</div>
Bare in mind that:
It wont necessarily be a div, it could be <h2 class="blah">
The class can have more than one class and still needs to be replaced e.g. <div class="foo blah green">hello world</div>
I am thinking regular expressions should be able to do this, if not I am open to other suggestions such as using the DOM class (although I would rather avoid this if possible because it has to be PHP4 compatible).
Do not use regular expressions to parse HTML. You can use the built in DOMDocument, or something like simple_html_dom:
require_once("simple_html_dom.php");
$class = "blah";
$content = "new content";
$html = '<div class="blah">hello world</div>';
$doc = new simple_html_dom();
$doc->load($html);
foreach ( $doc->find("." . $class) as $node ) {
$node->innertext = $content;
}
Sorry, I didn't see the PHP4 requirement. Here's a solution using the standard DOMDocument as mentioned above.
function DOM_getElementByClassName($referenceNode, $className, $index=false) {
$className = strtolower($className);
$response = array();
foreach ( $referenceNode->getElementsByTagName("*") as $node ) {
$nodeClass = strtolower($node->getAttribute("class"));
if (
$nodeClass == $className ||
preg_match("/\b" . $className . "\b/", $nodeClass)
) {
$response[] = $node;
}
}
if ( $index !== false ) {
return isset($response[$index]) ? $response[$index] : false;
}
return $response;
}
$doc = new DOMDocument();
$doc->loadHTML($html);
foreach ( DOM_getElementByClassName($doc, $class) as $node ) {
$node->nodeValue = $content;
}
echo $doc->saveHTML();
If you are sure that $html is valid HTML code, you could use a HTML parser or even XML parser if it's valid XML code.
But the quick and dirty way in Regex would be something like:
$html = preg_replace('/(<[^>]+ class="[^>]*' . $class . '[^"]*"[^>]*>)[^<]+(<\/[^>]+>)/siU', '$1' . $content . '$2', $html);
Didn't test it too much, but it should work. Tell me if you find cases where it doesn't. ;)
Edit: Added "and dirty"... ;)
Edit 2: New version of the RegEx:
<?php
$class = "blah";
$content = "new content";
$html = '<div class="blah test"><h1><span>hello</span> world</h1></div><div class="other">other content</div><h2 class="blah">remove this</h2>';
$html = preg_replace('/<([\w]+)(\s[^>]*class="[^"]*' . $class . '[^"]*"[^>]*>).+(<\/\\1>)/siU', '<$1$2' . $content . '$3', $html);
echo $html;
?>
The last problem left is if theres a class that only has "blah" in its name, like "tooMuchBlahNow". Let's see how we can address that. Btw: Is it obvious already that I love playing with RegEx? ;)
There is no need to use the DOM class, this would probably be done quickest using jQuery, as Khnle said, or you could use the preg_replace() function. Give me some time, I may write a quick regex for you.
But I would recommend using something like jQuery, this way you can serve the page up to the user quickly and allow their computer to do the processing instead of your server.