在大家的帮助下,我写了一个脚本。希望这将帮助许多与我的问题相同的解决方案寻求者。
<?php
$url='http://php.net/';
$returned_content = get_url_contents($url);
/* gets the data from a URL */
function get_url_contents($url){
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
$doc = new DOMDocument();
$doc->loadHTML($returned_content);
$imageTags = $doc->getElementsByTagName('img');
$img1 = array();
foreach($imageTags as $tag) {
$img1[] = $tag->getAttribute('src');
}
foreach($img1 as $i){
save_image($i);
if(getimagesize(basename($i))){
echo '<h3 style="color: green;">Image ' . basename($i) . ' Downloaded OK</h3>';
}else{
echo '<h3 style="color: red;">Image ' . basename($i) . ' Download Failed</h3>';
}
}
//Alternative Image Saving Using cURL seeing as allow_url_fopen is disabled - bummer
function save_image($img1,$fullpath='http://example.com/'){
if($fullpath=='http://example.com/'){
$fullpath = basename($img1);
}
$ch = curl_init ($img1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);
if(file_exists($fullpath)){
unlink($fullpath);
}
$fp = fopen($fullpath,'x');
fwrite($fp, $rawdata);
fclose($fp);
}
?>