Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract all img tag within an anchor tag?

I would like to extract all img tags that are within an anchor tag using the PHP DOM object.

I am trying it with the code below but its getting all anchor tag and making it's text empty due the inside of an img tag.

function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    @$xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <a> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) 
    {
       $hrefval = '';
       if(strpos($link->getAttribute('href'),'www') > 0)
       {
           //$links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
           $hrefval = '#URL#'.$link->getAttribute('href').'#TEXT#'.$link->nodeValue;
           $links[$hrefval] = $hrefval;
       }
       else
       {
           //$links[] = array('url' => GetMainBaseFromURL($url).$link->getAttribute('href'), 'text' => $link->nodeValue);
           $hrefval = '#URL#'.GetMainBaseFromURL($url).$link->getAttribute('href').'#TEXT#'.$link->nodeValue;
           $links[$hrefval] = $hrefval;
       }
    }

    foreach($xml->getElementsByTagName('img') as $link) 
    {
        $srcval = '';
       if(strpos($link->getAttribute('src'),'www') > 0)
       {
           //$links[] = array('src' => $link->getAttribute('src'), 'nodval' => $link->nodeValue);
           $srcval = '#SRC#'.$link->getAttribute('src').'#NODEVAL#'.$link->nodeValue;
           $links[$srcval] = $srcval;
       }
       else
       {
           //$links[] = array('src' => GetMainBaseFromURL($url).$link->getAttribute('src'), 'nodval' => $link->nodeValue);    
           $srcval = '#SRC#'.GetMainBaseFromURL($url).$link->getAttribute('src').'#NODEVAL#'.$link->nodeValue;
           $links[$srcval] = $srcval;

       }
    }

    //Return the links
    //$links = unsetblankvalue($links);
    return $links;
} 

This returns all anchor tag and all img tag separately.

like image 240
Bajrang Avatar asked Jan 01 '26 11:01

Bajrang


1 Answers

$xml = new DOMDocument;
libxml_use_internal_errors(true);
$xml->loadHTMLFile($url);
libxml_clear_errors();
libxml_use_internal_errors(false);
$xpath = new DOMXPath($xml);
foreach ($xpath->query('//a[contains(@href, "www")]/img') as $entry) {
    var_dump($entry->getAttribute('src'));
}
like image 179
cloakedninjas Avatar answered Jan 03 '26 01:01

cloakedninjas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!