简体   繁体   English

PHP / AJAX Image Grabbing脚本类似于Facebook消息传递功能

[英]PHP/AJAX Image Grabbing script similar to functionality Facebook messaging

When sending a message on Facebook, if you include a URL it generally grabs a picture from the webpage and adds it at the bottom as a thumbnail. 在Facebook上发送消息时,如果包含URL,则通常会从网页中抓取图片并将其作为缩略图添加在底部。 You then have the ability to select through a number of pictures featured on the site. 然后,您可以从网站上精选的许多图片中进行选择。

I can see how this could be built, but to save me the hassle I wonder if somebody has already done it already in a publicly available format? 我可以看到它是如何构建的,但是为了避免麻烦,我想知道是否有人已经以可公开使用的格式进行了此操作?

Thanks! 谢谢!

Alright, the code sample I prepared for you was too long to add as a comment of the first. 好了,我为您准备的代码示例太长,无法添加为第一个示例的注释。 So here's the correct code, verified to work on my local PHP environment (5.3.1): 因此,这是经过验证可在我的本地PHP环境(5.3.1)上运行的正确代码:

<?php
/**
 * Sample CURL Image Extractor
 * 
 * Prepared for stackoverflow.com 
 *
 * @author Sam Skjonsberg <skoneberg@gmail.com>
 **/

if(!function_exists('json_encode'))
{
    die('You need at least PHP 5.2 to use this script.');
}

//
// JSON & No-Cache Headers
// Uncoment when implemented as an actual JSON service
//
//header('Cache-Control: no-cache, must-revalidate');
// Date in the past to ensure it isn't cached
//header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
//header('Content-type: application/json');
//

//$url      =   parse_url($_REQUEST['url']);
// Harcoded url for demonstration
// Shameless self-plug :)
$url        =   'http://www.codeviking.net';

if(!empty($url))
{       

    if(!preg_match('%^https?://%i', $url))
    {
        echo get_json_error('Invalid URL');
    }

    $ch     =   curl_init();

    curl_setopt_array(  
                        $ch,    
                        array
                        (
                            CURLOPT_URL             =>  $url,
                            CURLOPT_RETURNTRANSFER  =>  true,
                            CURLOPT_FOLLOWLOCATION  =>  true
                        )
                     );

    $html   =   curl_exec($ch);

    if(!empty($html)) 
    {
        $doc                =   new DOMDocument($html);

        $doc->loadHTML($html);

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

        $image_srcs         =   array();

        foreach($images as $img) {
            foreach($img->attributes as $attribute_name => $attribute_node)
            {
                if($attribute_name == 'src')
                {
                    $src            =   $attribute_node->nodeValue;

                    // Parse image into absolute URL
                    if(!preg_match('%^https?://%i', $src))
                    {
                        $src    =   $url . '/' . preg_replace('%^\.?/%', '', $src);                         
                    }

                    $image_srcs[]   =   $src;

                }
            }
        }

        echo json_encode($image_srcs);  

        // And there you have it, a collection of image
        // paths to parse through on the client and add <img src="image_src" /> for each.
        //
        // So, for instance as your ajax success callback
        //
        //
        // var images = parseJSON(image_json);
        // for(var i = 0; i < images.length; i++)
        // {
        //  image_src = images[i];
        //  /* Requires jQuery */
        //  $('body').append($('<img />').attr('src', image_src));
        // }
    } 
    else 
    {
        echo get_json_error('Invalid URL');
    }
} 
else 
{
    echo get_json_error('Invalid URL');
}

function get_json_error($msg)
{   
    $error  =   array('error' => $msg);
    return json_encode($error);
}

That really should work. 那真的应该工作。 Also I'd appreciate a vote up on the answer as I'm trying to break the 100 point mark! 另外,我也很想对答案投赞成票,因为我正试图突破100分! Thanks and good luck! 谢谢,祝你好运!

Really shouldn't be hard to implement. 确实不难实现。 Coding is fun, take this and roll with it: 编码很有趣,请顺其自然:

$ch = curl_init();

curl_setopt_array($ch, array(CURLOPT_URL => $_POST['url'], CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER, true));

$results = curl_exec($ch);

$doc = new DOMDocument();

$doc->loadHTML($results);

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

This should return a DOMNodeList I believe -- from there you iterate through and pull out the src attribute for each image, stick it into json_encode(), and then write a nice webservice to submit a url and return the nice little collection of images. 我应该相信这会返回一个DOMNodeList,从那里开始遍历并为每个图像拉出src属性,将其粘贴到json_encode()中,然后编写一个不错的Web服务以提交url并返回漂亮的少量图像集合。

I realize its not what you're asking for, but its a start. 我意识到这不是您要的,而是一个开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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