从URL抓取图像并显示它们

时间:2011-07-20 07:17:01

标签: php javascript

我对javascript中的文档对象模型有疑问 我正在尝试构建一个从url抓取图像并输出它们的程序,我实际上是在php中使用下面的代码完成的,但我的问题是如何在javascript中执行相同的功能?

<?php

    $url = 'http://lockerz.com/s/104049300';    

    $doc = new DOMDocument();    
    @$doc->loadHTMLFile($url);

    // Get all images
    $images_list = $doc->getElementsByTagName('img');

    foreach($images_list as $image) {      
      echo $image;
    }

?>

3 个答案:

答案 0 :(得分:2)

您无法使用ajax向http://lockerz.com/发送请求(假设它不是您自己的域),因此您无论如何都需要一些服务器端脚本。您可能只是使用您在php中工作的内容,但更改它以将url作为参数并返回一个JSON数组,如:

<?php

    $url = $_GET['url'];
    // sanitize url here, possible verify that it begins with http://lockerz.com, or something    

    $doc = new DOMDocument();    
    @$doc->loadHTMLFile($url);

    // Get all images
    $images_list = $doc->getElementsByTagName('img');

    $out = '[';
    foreach($images_list as $image) {      
      $out .= $image.',';
    }

    echo substr($out, 0, -1).']';

?>

然后使用javascript将ajax请求发送到您自己的php页面,并使用返回的数组执行您想要的操作。

答案 1 :(得分:0)

基于AJAX或iframe的纯客户端解决方案将违反the same origin policy。这是一次使用AJAX(或iframe)获取不在您网站上的网页,浏览器将禁止此行为。

我建议使用服务器端获取页面并将其传递回客户端。

服务器端:http://your-host/fetch.php

<?php
$url = $_GET['url'];
echo file_get_contents($url);
?>

客户端(基于jQuery):

<script>
    $.get('http://your-host/fetch.php', {url: 'http://lockerz.com/s/104049300'}, function(data) {
        var imgs = $('<div/>').html(data).find('img');
        imgs.each(function(i, img) {
            alert(img.src); // show a dialog containing the url of image
        });
    });
</script>

答案 2 :(得分:-1)

您可以使用jQuery .load()方法获取网站的内容。 获得html后,您可以解析html源代码。

http://api.jquery.com/load/

希望有所帮助

相关问题