douchuanghan1344 2017-04-24 22:39
浏览 16
已采纳

使用php从url中抓取图像

i am trying to make a page that allows me to grab and save images from another link , so here's what i want to add on my page:

  1. text box (to enter url that i want to get images from).
  2. save dialog box to specify the path to save images.

but what i am trying to do here i want to save images only from that url and from inside specific element.

for example on my code i say go to example.com and from inside of element class="images" grab all images.

notes: not all images from the page, just from inside the element whether element has 3 images in it or 50 or 100 i don't care.

here's what i tried and worked using php

<?php
$html = file_get_contents('http://www.tgo-tv.net');
preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i',$html, $matches ); 
echo $matches[ 1 ][ 0 ];
?>

this gets image name and path but what i am trying to make is a save dialog box and the code must save image directly into that path instead of echo it out

hope you understand

Edit 2

it's ok of Not having save dialog box. i must specify save path from the code

  • 写回答

2条回答 默认 最新

  • dongzaliang4492 2017-04-24 22:58
    关注

    If you want something generic, you can use:

    <?php
        $the_site = "http://somesite.com";
        $the_tag = "div"; #
        $the_class = "images";
    
        $html = file_get_contents($the_site);
        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
    
        foreach ($xpath->query('//'.$the_tag.'[contains(@class,"'.$the_class.'")]/img') as $item) {
    
            $img_src =  $item->getAttribute('src');
            print $img_src."
    ";
    
        }
    

    Usage:

    Change the site, tag, which can be a div, span, a, etc. also change the class name.

    For example, change the values to:

    $the_site = "https://stackoverflow.com/questions/23674744/what-is-the-equivalent-of-python-any-and-all-functions-in-javascript";
    $the_tag = "div"; #
    $the_class = "gravatar-wrapper-32";
    

    Output:

    https://www.gravatar.com/avatar/67d8ca039ee1ffd5c6db0d29aeb4b168?s=32&d=identicon&r=PG
    https://www.gravatar.com/avatar/24da669dda96b6f17a802bdb7f6d429f?s=32&d=identicon&r=PG
    https://www.gravatar.com/avatar/24780fb6df85a943c7aea0402c843737?s=32&d=identicon&r=PG
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办