开发者

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. You then ha开发者_JAVA百科ve 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
/**
 * 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! 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.

I realize its not what you're asking for, but its a start.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜