<html>
<body>
<?php
$html='<html>
<body>
<p>
Illustrating wget -r , with images too
</p>
<p>
This is the first image
<img src="abc.JPG" alt="First Captured Image"/>
</p>
<p>
This is the second image
<img src="def.JPG" alt="Second Captured Image"/>
</p>
</body>
</html>';
echo($html);
$dom = new domDocument;
#$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $image->getAttribute('src');
echo $alter->get Attribute('alt');
echo "<img sr='$image'/>";
}
</body>
</html>
My code is to parse the images in the html code above and then use php to echo it again.
This is my sample code. How do I echo the above html code, using php, and display in the same way?
I tried doing this, but I cant place image in exactly the same position as where I retrieved. I don't want to use "header(contents)"
Your statement echo "<img sr='$image'/>"; is incorrect. The correct one is
echo "<img src='$image'/>";
Related
This is my content:
<p><img src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
This is my PHP code:
function convert_the_content($content){
$content = preg_replace('/<p><img.+src=[\'"]([^\'"]+)[\'"].*>/i', "<p class=\"uploaded-img\"><img class=\"lazy-load\" data-src=\"$1\" /></p>", $content);
return $content;
}
I using my code to add a class for <p> tag and <img> tag and to convert src="" to data-src="".
The problem that my code has removed the width and the height attr from <img> tag, So my question is how can i change my code to work and getting this details with it too?
NOTE: My content may have many of <img> and <p> tags.
If you only have this very exact HTML snippet, you can do it simpler by just doing
$html = <<< HTML
<p><img src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
HTML;
$html = str_replace('<p>', '<p class="foo">', $html);
$html = str_replace(' src=', ' data-src=', $html);
echo $html;
This will output
<p class="foo"><img data-src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
If you are trying to convert arbitrary HTML, consider using a DOM Parser instead:
<?php
$html = <<< HTML
<html>
<body>
<p><img src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
<p><img width="215" height="1515" src="http://localhost/contents/uploads/2017/11/1.png"></p>
<p ><img
class="blah"
height="1515"
width="215"
src="http://localhost/contents/uploads/2017/11/1.png"
>
</p>
</body>
</html>
HTML;
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_use_internal_errors(false);
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate('//p[img]') as $paragraphWithImage) {
$paragraphWithImage->setAttribute('class', 'foo');
foreach ($paragraphWithImage->getElementsByTagName('img') as $image) {
$image->setAttribute('class', trim('bar ' . $image->getAttribute('class')));
$image->setAttribute('data-src', $image->getAttribute('src'));
$image->removeAttribute('src');
}
};
echo $dom->saveHTML($dom->documentElement);
Output:
<html><body>
<p class="foo"><img width="215" height="1515" class="bar" data-src="http://localhost/contents/uploads/2017/11/1.jpg"></p>
<p class="foo"><img width="215" height="1515" class="bar" data-src="http://localhost/contents/uploads/2017/11/1.png"></p>
<p class="foo"><img class="bar blah" height="1515" width="215" data-src="http://localhost/contents/uploads/2017/11/1.png"></p>
</body></html>
I have a string containing different types of html tags and stuff, including some <img> elements. I am trying to wrap those <img> elements inside a <figure> tag. So far so good using a preg_replace like this:
preg_replace( '/(<img.*?>)/s','<figure>$1</figure>',$content);
However, if the <img>tag has a neighboring <figcaption> tag, the result is rather ugly, and produces a stray end tag for the figure-element:
<figure id="attachment_9615">
<img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" />
<figcaption class="caption-text"></figure>Caption title here</figcaption>
</figure>
I've tried a whole bunch of preg_replace regex variations to wrap both the img-tag and figcaption-tag inside figure, but can't seem to make it work.
My latest try:
preg_replace( '/(<img.*?>)(<figcaption .*>*.<\/figcaption>)?/s',
'<figure">$1$2</figure>',
$content);
As others pointed out, better use a parser, i.e. DOMDocument instead. The following code wraps a <figure> tag around each img where the next sibling is a <figcaption>:
<?php
$html = <<<EOF
<html>
<img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" />
<figcaption class="caption-text">Caption title here</figcaption>
<img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" />
<img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" />
<figcaption class="caption-text">Caption title here</figcaption>
</html>
EOF;
$dom = new DOMdocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
# get all images
$imgs = $xpath->query("//img");
foreach ($imgs as $img) {
if ($img->nextSibling->tagName == 'figcaption') {
# create a new figure tag and append the cloned elements
$figure = $dom->createElement('figure');
$figure->appendChild($img->cloneNode(true));
$figure->appendChild($img->nextSibling->cloneNode(true));
# insert the newly generated elements right before $img
$img->parentNode->insertBefore($figure, $img);
# and remove both the figcaption and the image from the DOM
$img->nextSibling->parentNode->removeChild($img->nextSibling);
$img->parentNode->removeChild($img);
}
}
$dom->formatOutput=true;
echo $dom->saveHTML();
See a demo on ideone.com.
To have a <figure> tag around all your images, you might want to add an else branch:
} else {
$figure = $dom->createElement('figure');
$figure->appendChild($img->cloneNode(true));
$img->parentNode->insertBefore($figure, $img);
$img->parentNode->removeChild($img);
}
i want replace all images on my html but the code replace one and escaping one and so on
i use DOMDocument to replace images on my content and i use the next code the problem is the code escaping image
for example
1 2 3 4 images the code replace one and three and escaping tow and four and so on
$dom = new \DOMDocument();
$dom->loadHTML("data"));
$dom->preserveWhiteSpace = true;
$count = 1;
$images = $dom->getElementsByTagName('img');
foreach ($images as $img) {
$src = $img->getAttribute('src');
$newsrc = $dom->createElement("newimg");
$newsrc->nodeValue = $src;
$newsrc->setAttribute("id","qw".$count);
$img->parentNode->replaceChild($newsrc, $img);
$count++;
}
$html = $dom->saveHTML();
return $html;
the html code is
<p><img class="img-responsive" src="http://www.jarofquotes.com/img/quotes/86444b28aa86d706e33246b823045270.jpg" alt="" width="600" height="455" /></p>
<p> </p>
<p>some text</p>
<p> </p>
<p><img class="img-responsive" src="http://40.media.tumblr.com/c0bc20fd255cc18dca150640a25e13ef/tumblr_nammr75ACv1taqt2oo1_500.jpg" alt="" width="480" height="477" /></p>
<p> </p>
<p><span class="marker"><img class="img-responsive" src="http://wiselygreen.com/wp-content/uploads/green-living-coach-icon.png" alt="" width="250" height="250" /><br /><br /></span></p>
i want output html replace all images with
<newimg>Src </newimg>
Ok, I couldn't find a dupe suitable for PHP, so I am answering this one.
The issue you are facing is that NodeLists returned by getElementsByTagName() are live list. That means, when you do the call to replaceChild(), you are altering the NodeList you are currently iterating.
Let's assume we have this HTML:
$html = <<< HTML
<html>
<body>
<img src="1.jpg"/>
<img src="2.jpg"/>
<img src="3.jpg"/>
</body>
</html>
HTML;
Now let's load it into a DOMDocument and get the img elements:
$dom = new DOMDocument;
$dom->loadHTML($html);
$allImages = $dom->getElementsByTagName('img');
echo $allImages->length, PHP_EOL;
This will print 3 because there is 3 img elements in the DOM right now.
Let's replace the first img element with a p element:
$allImages->item(0)->parentNode->replaceChild(
$dom->createElement("p"),
$allImages->item(0)
);
echo $allImages->length, PHP_EOL;
This now gives 2 because there is now only 2 img elements left, essentially
item 0: img will be removed from the list
item 1: img will become item 0
item 2: img will become item 1
You are using foreach, so you are first replacing item 0, then move on to item 1, but item 1 is now item 2 and the item 0 is item 1 you would expect next. But because the list is live, you are skipping it.
To get around this, use a while loop and always replace the first element:
while ($allImages->length > 0) {
$allImages->item(0)->parentNode->replaceChild(
$dom->createElement("p"),
$allImages->item(0)
);
}
This will then catch all the img elements.
Basically what I'm trying to achieve is replacing the content of the src-attributes of a bunch of img-nodes by the content of the corresponding data-src-nodes in a page like the following one.
<html>
<body>
<div id="a">
<img src="" data-src="myValue" />
<img src="" data-src="myValue2" />
</div>
<img src="" data-src="myValue" />
</body>
</html>
I want to do this by finding a common base node (in this case the img nodes in the div with id a) and based on that node
the node containing the value to copy and#
the node retrieving the value
Script
<?PHP
$html = '<html><body><div id="a"><img src="" data-src="myValue"/><img src="" data-src="myValue2"/></div><img src="" data-src="myValue"/></body></html>';
$doc = new DOMDocument();
#$doc->loadHTML($html);
$basenode = false;
$xpath = new DOMXPath($doc);
$entries = $xpath->query('(//div[#id="a"])');
if ($entries->length > 0) $basenode = $entries->item(0);
if ($basenode) {
$img = $xpath->query('//img', $basenode);
foreach ($img as $curImg) {
$from = $xpath->query('//#data-src', $curImg);
$to = $xpath->query('//#src', $curImg);
$to->item(0)->value = $from->item(0)->value;
}
echo $doc->saveXML();
}
?>
Expected output
<html>
<body>
<div id="a">
<img src="myValue" data-src="myValue" />
<img src="myValue2" data-src="myValue2" />
</div>
<img src="" data-src="myValue" />
</body>
</html>
Actual output
<html>
<body>
<div id="a">
<img src="myValue" data-src="myValue" />
<img src="" data-src="myValue2" />
</div>
<img src="" data-src="myValue" />
</body>
</html>
So, the line
$from = $xpath->query('//#data-src', $curImg);
seems to actually base its search on the root node and not the img-node selected before. How can I solve this?
(I know that a possible workaround would be to omit selecting the img-nodes explicitly and doing something like from='//div[#id="a"]/img/#data-src' and to='//div[#id="a"]/img/#src' but I'm a bit concerned, that I might end up copying values between attributes of different nodes)
/ at the beginning specifies an absolute location path (i.e, from the document root). Instead, you want to use a relative one (relative to the context node).
For example; .//#data-src, or descendant::img/#data-src, and so on.
I have page image.php
where images are kept in container like below :- Note: There are other Images outside container div too.. i just want images from container div.
<!DOCTYPE html>
<head>
<title>Image Holder</title>
</head>
<body>
<header>
<img src="http://examepl.com/logo.png">
<div id="side">
<div id="facebook"><img src="http://examepl.com/fb.png"></div>
<div id="twiiter"><img src="http://examepl.com/t.png"></div>
<div id="gplus"><img src="http://examepl.com/gp.png"></div>
</div>
</header>
<div class="container">
<p>SOme Post</p>
<img src="http://examepl.com/some.png" title="some image" />
<p>SOme Post</p>
<img src="http://examepl.com/some.png" title="some image" />
<p>SOme Post</p>
<img src="http://examepl.com/some.png" title="some image" />
</div>
<footer>
<div id="foot">
copyright © 2013
</div>
</footer>
</body>
</html>
and i am trying to fetch only image from my image.php file with preg_match_all, but it returns boolean(false) :(
my php code :-
<?php
$file = file_get_contents("image.php");
preg_match_all("/<div class=\"container\">(.*?)</div>/", $file, $match);
preg_match_all("/<img src=\"(.*?)\">/", $match, $images);
var_dump($images);
?>
Both the files are in root folder , and now i am getting blank page :(
Any help would be great
Thanks
I think this will work for you try the link below to test your regex
preg_match_all("/<div class=\"container\">(.*?)<\/div>/", $file, $match);
preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/", $match[1][0], $images);
http://www.phpliveregex.com
You better not use regex for this purpose. PHP provides nice DOM api for this purpose. Consider code like below:
$html = <<< EOF
<div class="container">
<p>SOme Post</p>
<img src="http://examepl.com/some1.png" title="some image" />
<p>SOme Post</p>
<img src="http://examepl.com/some2.png" title="some image" />
<p>SOme Post</p>
<img src="http://examepl.com/some3.png" title="some image" />
</div>
EOF;
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//div[#class='container']/img");
$img = array();
for($i=0; $i < $nodelist->length; $i++) {
$node = $nodelist->item($i);
$img[] = $node->getAttribute('src');
}
print_r($img);
OUTPUT:
Array
(
[0] => http://examepl.com/some1.png
[1] => http://examepl.com/some2.png
[2] => http://examepl.com/some3.png
)
Live Demo: http://ideone.com/iBhVMF
You can easily obtain what you want with an XPath query:
$url = 'http://examepl.com/image.php';
$doc = new DOMDocument();
#$doc->loadHTMLFile($url);
$xpath = new DOMXPath($doc);
$srcs = $xpath->query("//div[#class='container']//img/attribute::src");
foreach ($srcs as $src) {
echo '<br/>' . $src->value;
}
preg_match_all("/<img src=\"(.*?)\">/", $match, $images);
replace with
preg_match_all("/<img src=\"(.*?)\"/", $match, $images); // stripped ">" char