简体   繁体   中英

I am trying to get images from other website but code is not working

I am new to php language it will be great to get the. URL on text box and click on the button then show all the images from that URL in a div of your page by using object oriented PHP and regular expression.

<?php

if(isset($_POST["btnGo"])){
  $url=$_POST["txtUrl"];    
  $obj=new ImageExtractor();
  $obj->extract_image2($url);
}

//class ImageExtractor
class ImageExtractor{

 //method 1
  function extract_image($url){ 
    $html=file_get_contents($url);  
    preg_match_all('/<img[^>]+src=([\'"])([^"\']+)\1/i',$html,$matches);

    foreach($matches[2] as $image){     
    echo "<img src='".$image."' width='200' height='100' style='margin:5px;' />";
    }
  }

 //method 2
 function extract_image2($url){
    $html = file_get_contents($url);

    $doc = new DOMDocument();
    @$doc->loadHTML($html);

    $tags = $doc->getElementsByTagName('img');

    foreach ($tags as $tag) {
               echo "<img src='".$tag->getAttribute('src')."' width='200' height='100' style='margin:5px;' />";
    }
   }
}

?>
<form action="#" method="post">
<input type="text" name="txtUrl" value="https://yahoo.com" placeholder="Enter URL" />
<input type="submit" name="btnGo" value="Go"/>
</form>

try this code :

<?php

if(isset($_POST["btnGo"])){
  $url=$_POST["txtUrl"];   
  $obj=new ImageExtractor();
  $obj->extract_image2($url);
}

//class ImageExtractor
class ImageExtractor{

 //method 1
  function extract_image($url){ 
    $html=file_get_contents($url);  
    preg_match_all('/<img[^>]+src=([\'"])([^"\']+)\1/i',$html,$matches);

    foreach($matches[2] as $image){     
    echo "<img src='".$url."/".$image."' width='200' height='100' style='margin:5px;' />";
    }
  }

 //method 2
 function extract_image2($url){
    $html = file_get_contents($url);
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $tags = $doc->getElementsByTagName('img');
    foreach ($tags as $tag) {
               echo "<img src='".$url."/".$tag->getAttribute('src')."' width='200' height='100' style='margin:5px;' />";
    }
   }
}
?>
<form action="#" method="post">
<input type="text" name="txtUrl" value="http://tinamo.ir" placeholder="Enter URL" />
<input type="submit" name="btnGo" value="Go"/>
</form>

but this code dosn't work on all sites, you can leach images to your space and show that images from your space (host) Regards Soroush

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM