etrader Posted February 20, 2011 Share Posted February 20, 2011 It is easy to get image or link by DomDocument, but I did not find a way to get image with its target link. Imagine a html as <div class=image> <a href='http://site.com'><img src='imagelink.jpg'></a> </div> How to get both the image link and href? $dom = new DOMDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $hrefs = $xpath->evaluate("/html/body//div[@class='image']"); for ($i = 0; $i < $hrefs->length; $i++) { $href = $hrefs->item($i); Now to get the image and its href, we need first getElementsByTagName('a') and getElementsByTagName('img') but they do not work inside foreach. What's your idea? Link to comment https://forums.phpfreaks.com/topic/228271-getting-image-with-its-link-by-domdocument/ Share on other sites More sharing options...
silkfire Posted February 20, 2011 Share Posted February 20, 2011 If I were you I would refrain from using DOMDocument it's very unreliable. Please consider using regex instead which is very precise and powerful for parsing documents for example. This piece of code will return the URLs of all the links in the document that surround an image. preg_match_all('#class="image".*?a href='([^']+).*?img src#s', $html, $imglinks); foreach ($imglinks[1] as $imglink) echo $imglink; Link to comment https://forums.phpfreaks.com/topic/228271-getting-image-with-its-link-by-domdocument/#findComment-1177116 Share on other sites More sharing options...
etrader Posted February 20, 2011 Author Share Posted February 20, 2011 Nice idea, but I got an error PHP Parse error: syntax error, unexpected '(' in the preg_match_all line Link to comment https://forums.phpfreaks.com/topic/228271-getting-image-with-its-link-by-domdocument/#findComment-1177123 Share on other sites More sharing options...
BlueSkyIS Posted February 20, 2011 Share Posted February 20, 2011 need to escape the single quotes: preg_match_all('#class="image".*?a href=\'([^\']+).*?img src#s', $html, $imglinks); Link to comment https://forums.phpfreaks.com/topic/228271-getting-image-with-its-link-by-domdocument/#findComment-1177192 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.