I have a search engine which I have been playing with for some time now, and for some time now I wanted to add a new feature: display the article image when searching on my website. See example:
I have some code that I have bin playing around with, but it doesn't work when there are multiple links. Meaning it only displays the images of the first link. The engine has the entire code in a variable.
What I am trying to get is a php/js(jquery) code, that parses a link - provide by the search engine - in the $url
variable, that it will search for the a
tag within it, the img
with the class name article-image
. it then display it in the a
tag with the id searchimage
. Might be better to turn that in a class, but I'll rely on you guys on what is the better option.
External link with the img:
<a class="article-image" title="Qtox" href="http://i.imgur.com/GePjpxg.png"> <img src="http://i.imgur.com/GePjpxg.png" alt="Qtox"> </a>
The search engine when founded more links, will use the same template, so the code has to be used again and again.
Here is the code I have so far that I have reused so far:
<?php
$tagName = 'img';
$articlimageclass = "article-image";
$dom = new DOMDocument;
$dom->preserveWhiteSpace = true;
@$dom->loadHTMLFile("$url");
$linkimg = getTags($dom, $tagName);
?>
<?php
function getTags($dom, $tagName) {
$linkimg = get_class($articlimageclass);
$domxpath = new DOMXPath($dom);
$newDom = new DOMDocument;
$newDom->formatOutput = false;
$filtered = $domxpath->query("//$tagName");
$i = 0;
while( $myItem = $filtered->item($i++) ){
$node = $newDom->importNode( $myItem, true );
$newDom->appendChild($node);
}
$linkimg = $newDom->saveHTML();
// return "<b>$html</b>";
echo "$linkimg";
}
?>
I am novice in php and etc. So I hope some of you will help me on this!
I don't work with DOMDocument
at all so this is just a guess. You can modify your function a bit to do this:
function makeImageLink($dom, className) {
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$domxpath = new DOMXPath($dom);
$newDom = new DOMDocument;
$newDom->formatOutput = false;
if(isset($className){
$filtered = $domxpath->query("//a[class='$className']");
} else {
return false;
}
foreach($filtered as $a){
$href = $a->getAttribute("href");
$ext = strtolower(pathinfo($href, PATHINFO_EXTENSION)); // Using strtolower to overcome case sensitive
if (in_array($ext, $supported_image)) {
$a->innerHTML = "<img src='$href'>";
}
}
}
To do this in JQuery (in the browser) it would be:
var a = $("a[class='article-image']");
var supportedImages = array('.gif', '.jpg', '.jpeg', '.png');
$.each(a, function(k, v)){
var imgType = $(this).substring($(this).lastIndexOf("."));
if(supportImages.indexOf(imgType)){
$(this).html("<img src='" + $(this).attr('href') + "'>");
}
}