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 <[email protected]>
**/
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!