Forum Moderators: coopster

Message Too Old, No Replies

How to extract values from html code using php?

         

Thaparian

6:44 am on Jan 22, 2012 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hi,

I need to extract link url and image url from a peace of html code.

Sample HTML code

<a href="link to full size image"><img src="medium size image path here"/></a>


Or

<img src="medium size image path here" alt ="" />



If a link is present, I need the full size image url, otherwise I need the medium size image path.


This is the code that I made, but I think this is not the right way to get this done.

<?php
$test="html code here";
$doc=new DOMDocument();
$doc->loadHTML("$test");
$xml=simplexml_import_dom($doc);

$images=$xml->xpath('//img');

foreach ($images as $img) {

$thumburl = $img['src'];
}

$href = preg_match('/\shref="(?<href>[^"]+)"/', $test, $match);


if ($href!="") {
$href = $match[1];
echo $href;
}
else {
echo $thumburl;
}
?>


Please help.