Search code examples
phpcurlxpathgetpicture

How I can get specific picture on a website using curl xpath in php


Through this code I can get the specific text but my problem is how I can get the specific picture on a website through this code. Can anyone help, I am stuck at this point.

<?php

ini_set('max_execution_time', 300);

function news($url,$path){

    $curl=curl_init($url);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $html=curl_exec($curl);

    if(!empty($curl)){

        $thispage= new DOMDocument;
        libxml_use_internal_errors(true);
        $thispage->loadHTML($html);
        libxml_clear_errors();
        $xpath=new DOMXPath($thispage);
        $status=$xpath->evaluate($path);
        return $status;
    }
}

$a= news('https://www.dawn.com/latest-news','string(/html/body/div[2]/div/main/div/div/div[1]/article[1]/h2/a)');

echo $a;

?>

Solution

  • Assuming you want the image the appears next to the first headline, the XPath is:

    function news($url,$path){
    
        $curl=curl_init($url);
    
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    
        $html=curl_exec($curl);
    
        if(!empty($curl)){
    
            $thispage= new DOMDocument;
            libxml_use_internal_errors(true);
            $thispage->loadHTML($html);
            libxml_clear_errors();
            $xpath=new DOMXPath($thispage);
            $status=$xpath->evaluate($path);
            return $status;
        }
    }
    
    $a= news('https://www.dawn.com/latest-news','string(/html/body/div[2]/div/main/div/div/div[1]/article[1]/figure/div/a/img/@src)');
    
    echo $a;