Search code examples
phpsimpledom

Fetch an image and get it in a new url


Suppose i have fetched a images using PHP Simple HTML DOM Parser and obtain it in a specific URL. Suppose it fetched a Image in a variable like

<?php include("simple_html_dom.php");
$webpage ="http://www.example.com";
$html = file_get_html($webpage);
foreach($html->find('img') as $element) {
echo $element->src . '<br>';  }
?>

Now is it possible to get this image in my own domain path, like
$new_img = 'http://mysite.com/some_image_address.JPEG';
I am a PHP beginner so please describe it


Solution

  • did you try vanilla php, you can try this
    Example:

        <?php
    function xsrc($url){
    return "http://www.my_site.com/myfolder/" . basename($url);
    }
    //Two liner
    $img = xsrc('http://www.example.com/free_images/treacle1.png');
    echo "<img src='$img' />";
    //One liner
    echo '<img src="' . xsrc('http://www.example.com/free_images/treacle.png') . '" />';
    //HEREDOC SYNTAX
    echo <<<IMG
    <img src="$img" />
    IMG;
    ?>
    <!-- HTML WITH INLINE PHP -->
    <img src="<?php echo xsrc('http://www.example.com/free_images/treacle.png');?>" />
    <img src="<?php echo $img;?>" />