foreach($divs as $element)
{
$img = $element->find('a', 0)->href.'<br>';
$img = str_replace("http://www.youtube.com/watch?v=", "http://img.youtube.com/vi/", $img);
echo $img."/mqdefault.jpg";
}
Now output is :
http://img.youtube.com/vi/UYkHcfrxxtk
/mqdefault.jpghttp://img.youtube.com/vi/ZgjaveCUsSg
/mqdefault.jpghttp://img.youtube.com/vi/TFVbehwl1Ns
/mqdefault.jpg
I want like this each img:
http://img.youtube.com/vi/UYkHcfrxxtk/mqdefault.jpg
How can get fix this? i used simple html dom.
echo $img."/mqdefault.jpg<br/>";
But if you are trying to make image elements on a page:
echo "<img src='".$img."' /><br/>";
use this.
remove .'<br>' from end of $img = $element->find('a', 0)->href.'<br>'; then add it to echo $img."/mqdefault.jpg";
<br> in html mean newline
$img = $element->find('a', 0)->href;
$img = str_replace("http://www.youtube.com/watch?v=", "http://img.youtube.com/vi/", $img);
echo $img."/mqdefault.jpg".'<br>';
Related
I'm trying to print a website's favicon, as an image, not as a link to it.
I have a php script in which I extract the favicon, but now I want to show it as it is.
Here is what I've tried.
//extract favicon
$url = $_POST['url'];
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML(file_get_contents($url));
$xml = simplexml_import_dom($doc);
$arr = $xml->xpath('//link[#rel="shortcut icon"]');
echo "<br>";
//echo "favicon:";
if( $arr)
{
$src = $arr[0]['href'];
echo "<img src = "$src">";//as I can see, the parameter here cannot be a variable
//second thing that I've tried: echo "<img src = "$arr[0]['href']""; it doesn't work either
}
This is what my script is echoing right now. http://i.stack.imgur.com/Wkoyj.jpg
Instead of the link to the favicon, I want the actual favicon to be displayed. I hope I explained myself correctly.
Your error is with the code:
echo "<img src = "$src">";//as I can see, the parameter here cannot be a variable
It should be
echo '<img src="'.$src.'">';
Or even
echo "<img src=\"$src\">";
I'm trying to show images from some directory using foreach.. But the problem is it's showing results in array, so if i want to print out first image I have to use $imag['0']..
Is there any way that I can bypass this number in this brackets?
Here's my code...
<?php
$domena = $_SERVER['HTTP_HOST'];
$galerija = $_POST['naziv'];
$galerija = mysql_real_escape_string($galerija);
define('IMAGEPATH', 'galleries/'.$galerija.'/');
foreach(glob(IMAGEPATH.'*') as $filename){
$imag[] = basename($filename);
?>
<img src="http://<?php echo $domena; ?>/galerija/galleries/<?php echo $galerija; ?>/<?php echo $imag['0']; ?>">
If you only need the first filename, then you could avoid the loop and directly access the first element of the array and use it afterwards:
$files = glob(IMAGEPATH.'*');
$filename = array_shift(array_values($files));
$image = basename($filename);
And to display it, you could use sprintf():
echo sprintf('<img src="http://%s/galerija/galleries/%s/%s"/>',
$domena, $galerija, $image);
Well you could first not create the array in the foreach statement and instead just print the img:
echo '<img src="', $domena ,'/galerija/galleries/', $galerija ,'/', $filename,'">';
Or you could iterate the array.
foreach($imag as $img): ?>
<img src="http://<?php echo $domena; ?>/galerija/galleries/<?php echo $galerija; ?>/<?php echo $img ?>">
<?php endforeach; ?>
So I've been at this for quite a while, and the best I got is wrapping the image in a link and with a span after the image tag:
<a href="">
<img src="">
<span></span>
</a>
But wat I want is:
<a href="">
<span></span>
<img src="">
</a>
I tried al kinds of variatons and positions of
$img->parentNode->appendChild($dom->createElement('span'), $img);
and the use of insertBefore() on all kinds of places in my code and I'm completely out of ideas since I'm fairly new to the php DOM stuff. My source:
foreach($dom->getElementsByTagName('img') as $img)
{
$fancyHref = $dom->createElement('a');
$clone = $fancyHref->cloneNode();
$img->parentNode->replaceChild($clone, $img);
$clone->appendChild($img);
$img->parentNode->appendChild($dom->createElement('span'));
};
Update:
To clarify my goal: I have an img tag in the html. After it goes through the php dom I want the img tag wrapped in an a tag with a span tag before the image tag:
Before
<img src="" />
After
<a href="">
<span class=""></span>
<img src="" />
</a>
My code at the moment for doing this (without the span)
foreach($dom->getElementsByTagName('img') as $img)
{
$src = $img->getAttribute('src');
$filename = substr(strrchr($src , '/') ,1);
$filename = preg_replace('/^[.]*/', '', $filename);
$filename = explode('.', $filename);
$filename = $filename[0];
if($this->imagesTitles[$this->currentLanguage][$filename] !== '')
{
$img->setAttribute('title', $this->imagesTitles[$this->currentLanguage][$filename]);
$img->setAttribute('alt', $this->imagesTitles[$this->currentLanguage][$filename]);
}
else
{
$img->removeAttribute('title');
$img->removeAttribute('alt');
}
$classes = explode(' ', $img->getAttribute('class'));
if(!in_array('no-enlarge', $classes))
{
$fancyHref = $dom->createElement('a');
$span = $dom->createElement('span');
$span->setAttribute('class', 'magnifier');
$fancyHref->setAttribute('class', 'enlarge');
$fancyHref->setAttribute('rel', 'enlarge');
$fancyHref->setAttribute('href', $img->getAttribute('src'));
if($img->getAttribute('title') !== '')
{
$fancyHref->setAttribute('title', $img->getAttribute('title'));
$fancyHref->setAttribute('alt', $img->getAttribute('title'));
}
$clone = $fancyHref->cloneNode();
$img->parentNode->replaceChild($clone, $img);
$clone->appendChild($img);
$img->parentNode->insertBefore($span, $img);
}
$img->setAttribute('class', trim(str_replace('no-enlarge', '', $img->getAttribute('class'))));
if($img->getAttribute('class') === '')
{
$img->removeAttribute('class');
}
}
You can use the DOMNode->insertBefore() method (docs). It has the form $parentNode->insertBefore( $nodeToBeInserted, $nodeToInsertBefore ). Your code would be:
$img->parentNode->insertBefore( $dom->createElement('span'), $img );
DOMNode->appendChild() (docs) only has 1 argument (the inserted node), and this node will always be inserted after the last childNode.
Edit:
I've now tested my code, and if you would replace $img->parentNode->appendChild($dom->createElement('span')); with my line in your test case, it would end up with the correct format. You are however manipulating elements in a very confusing way. Besides that, if I test your updated code, I either end up with your desired format, or without a span element at all...
The element you want to replace is the image, because that is the only element that is originally in the document. Therefore, you should clone -that- element. While your current code eliminates the hierarchy error, you are copying all the changed code, instead of just the conflicting element and that is a waste of memory and time. When you copy the conflicting element, it is easy. You append the elements to your a in the order you want them to appear. When you append the image, append the clone instead. Do not manipulate $img. If you need to manipulate the image, you have to manipulate the clone instead. Then you just replace $img by the elements you manipulated ($fancyHref in your case).
$html = '<img src="">';
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach($dom->getElementsByTagName('img') as $img) {
$fancyHref = $dom->createElement('a');
$clone = $img->cloneNode();
$span = $dom->createElement( 'span' );
#... do whatever you need to do to this span, the clone and the a element ...
#... when you are done, you can simply append all elements you have been manipulating ...
$fancyHref->appendChild( $span );
$fancyHref->appendChild( $clone );
$img->parentNode->replaceChild( $fancyHref, $img );
};
echo $dom->saveHTML();
Ummm. I know this may not classify as an answer, but don't you already have it? I mean.. I tried your code:
$dom = new DOMDocument;
$dom->loadHTMLFile("data.html");
foreach($dom->getElementsByTagName('img') as $img){
$src = $img->getAttribute('src');
$filename = substr(strrchr($src , '/') ,1);
$filename = preg_replace('/^[.]*/', '', $filename);
$filename = explode('.', $filename);
$filename = $filename[0];
$classes = explode(' ', $img->getAttribute('class'));
if(!in_array('no-enlarge', $classes))
{
$fancyHref = $dom->createElement('a');
$span = $dom->createElement('span');
$span->setAttribute('class', 'magnifier');
$fancyHref->setAttribute('class', 'enlarge');
$fancyHref->setAttribute('rel', 'enlarge');
$fancyHref->setAttribute('href', $img->getAttribute('src'));
if($img->getAttribute('title') !== '')
{
$fancyHref->setAttribute('title', $img->getAttribute('title'));
$fancyHref->setAttribute('alt', $img->getAttribute('title'));
}
$clone = $fancyHref->cloneNode();
$img->parentNode->replaceChild($clone, $img);
$clone->appendChild($img);
$img->parentNode->insertBefore($span, $img);
}
$img->setAttribute('class', trim(str_replace('no-enlarge', '', $img->getAttribute('class'))));
if($img->getAttribute('class') === ''){
$img->removeAttribute('class');
}
}
echo "<pre>" . htmlentities($dom->saveHTML()) . "</pre>";
With this (data.html) as source data:
<!doctype html>
<html>
<head>
</head>
<body>
<img src="http://lorempixel.com/g/400/200/" alt="alts" title="tits">
</body>
</html>
And the result is this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a class="enlarge" rel="enlarge" href="http://lorempixel.com/g/400/200/" title="tits" alt="tits">
<span class="magnifier">
</span>
<img src="http://lorempixel.com/g/400/200/" alt="alts" title="tits"></a>
</body>
</html>
So.. Isn't that what you wanted? :D
I want to modify the contents of an html file with php.
I am applying style to img tags, and I need to check if the tag already has a style attribute, if it has, I want to replace it with my own.
$pos = strpos($theData, "src=\"".$src."\" style=");
if (!$pos){
$theData = str_replace("src=\"".$src."\"", "src=\"".$src."\" style=\"width:".$width."px\"", $theData);
}
else{
$theData = preg_replace("src=\"".$src."\" style=/\"[^\"]+\"/", "src=\"".$src."\" style=\"width: ".$width."px\"", $theData);
}
$theData is the html source code I receive.
If a style attribute has not been found, I successfully insert my own style, but I think the problem comes when there is already a style attribute defined so my regex is not working.
I want to replace the style attribute with everything inside it, with my new style attribute.
How should my regex look?
Instead of using regex for this, you should use a DOM parser.
Example using DOMDocument:
<?php
$html = '<img src="http://example.com/image.jpg" width=""/><img src="http://example.com/image.jpg"/>';
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML('<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'.$html);
$dom->formatOutput = true;
foreach ($dom->getElementsByTagName('img') as $item)
{
//Remove width attr if its there
$item->removeAttribute('width');
//Get the sytle attr if its there
$style = $item->getAttribute('style');
//Set style appending existing style if necessary, 123px could be your $width var
$item->setAttribute('style','width:123px;'.$style);
}
//remove unwanted doctype ect
$ret = preg_replace('~<(?:!DOCTYPE|/?(?:html|body|head))[^>]*>\s*~i', '', $dom->saveHTML());
echo trim(str_replace('<meta http-equiv="Content-Type" content="text/html;charset=utf-8">','',$ret));
//<img src="http://example.com/image.jpg" style="width:123px;">
//<img src="http://example.com/image.jpg" style="width:123px;">
?>
Here is the regexp variant of solving this problem:
<?php
$theData = "<img src=\"/image.png\" style=\"lol\">";
$src = "/image.png";
$width = 10;
//you must escape potential special characters in $src,
//before using it in regexp
$regexp_src = preg_quote($src, "/");
$theData = preg_replace(
'/src="'. $regexp_src .'" style=".*?"/i',
'src="'. $src .'" style="width: '. $width . 'px;"',
$theData);
print $theData;
prints:
<img src="/image.png" style="width: 10px;">
Regex expression:
(<[^>]*)style\s*=\s*('|")[^\2]*?\2([^>]*>)
Usage:
$1$3
Example:
http://rubular.com/r/28tCIMHs50
Search for:
<img([^>])style="([^"])"
and replace with:
<img\1style="attribute1: value1; attribute2: value2;"
http://regex101.com/r/zP2tV9
way after str_replace function $img is empty and secont $img->find('img') function show error:
Fatal error: Cannot use object of type simple_html_dom as array in D:\wamp\www\test.php on line 7
<?php
require_once('simple_html_dom.php');
$img_html = str_get_html('hhtml tekst html tekst <img src = "img.png" /> ad sad');
foreach($img_html->find('img') as $element)
$img[] = $element->src . '<br>';
$img_html = str_replace($img[0], 'n-'.$img[0], $img_html);
foreach($img_html->find('img') as $element2)
echo $element2->src . '<br>';
?>
Is this really what you're aiming to do?
foreach($img->find('img') as $element)
$img[] = $element->src . '<br>';
$img is an object on the first foreach -loop, but then you're trying to access $img as an array, which is causing the error. Are you accidentally using the same variable name for two different things?
You have to put str_get_html before str_replace as:
$img_html = str_get_html('hhtml tekst html tekst <img src = "img.png" /> ad sad');
foreach($img_html->find('img') as $element)
$img[] = $element->src;
$img_html = str_get_html(str_replace($img[0], 'n-'.$img[0], $img_html));
foreach($img_html->find('img') as $element2)
echo $element2->src . '<br>';
Also check that you have given correct path in require_once( 'simple_html_dom.php');