0

我正在将来自外部站点的图像保存到我的 wordpress 主题中的文件夹中。而且我想知道是否可以两次调用 curl 或者一次就可以完成。

例子:

$data = get_url('http://www.veoh.com/watch/v19935546Y8hZPgbZ'); // getting the url first curl instance
preg_match('/fullHighResImagePath="(.*?)"/', $data, $thumbnail); // find the image from content
savePhoto($thumbnail, $post->ID); //2nd instance of curl to save the image

function get_url($url) {
$user_agent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2)";
    $ytc = curl_init(); // initialize curl handle 
    curl_setopt($ytc, CURLOPT_URL, $url); // set url to post to 
    curl_setopt($ytc, CURLOPT_FAILONERROR, 1);  // Fail on errors 
    curl_setopt($ytc, CURLOPT_FOLLOWLOCATION, 1); // allow redirects 
    curl_setopt($ytc, CURLOPT_RETURNTRANSFER, 1); // return into a variable 
    curl_setopt($ytc, CURLOPT_PORT, 80); //Set the port number 
    curl_setopt($ytc, CURLOPT_TIMEOUT, 15); // times out after 15s 
    curl_setopt($ytc, CURLOPT_HEADER, 1); // include HTTP headers
    curl_setopt($ytc, CURLOPT_USERAGENT, $user_agent);
    $source = curl_exec($ytc);
    curl_close($ytc);

     $data = trim( $source );
    return $data;
}

function savePhoto($remoteImage, $isbn) {
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $remoteImage);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
    $fileContents = curl_exec($ch);
    curl_close($ch);
    if (DIRECTORY_SEPARATOR=='/'){
        $absolute_path = dirname(__FILE__).'/'; 
    } else { 
        $absolute_path = str_replace('\\', '/', dirname(__FILE__)).'/'; 
    }
    $newImg = imagecreatefromstring($fileContents);
    return imagejpeg($newImg, $absolute_path ."video_images/{$isbn}.jpg",100);
}
4

1 回答 1

3

使用 Worpress 函数wp_remote_get并让 Wordpress 使用 curl 处理调用。

所以你可以做类似的事情

$data = my_get_remote_content('http://www.veoh.com/watch/v19935546Y8hZPgbZ');
// find the image from content
preg_match('/fullHighResImagePath="(.*?)"/', $data, $thumbnail); 
//2nd instance of curl to save the image
savePhoto(my_get_remote_content($thumbnail), $post->ID); 

function my_get_remote_content($url) {
  $response = wp_remote_get($url, 
    array(
      'headers' => array(
        'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2)'
      )
    )
  );
  if( is_wp_error( $response ) ) {
    throw new Exception('Error fetching remote content');
  } else {
    $data = wp_remote_retrieve_body($response);
    return $data;
  }  
}

function savePhoto($fileContents, $isbn) {
  if (DIRECTORY_SEPARATOR=='/'){
    $absolute_path = dirname(__FILE__).'/'; 
  } else { 
    $absolute_path = str_replace('\\', '/', dirname(__FILE__)).'/'; 
  }
  $newImg = imagecreatefromstring($fileContents);
  return imagejpeg($newImg, $absolute_path ."video_images/{$isbn}.jpg",100);
}
于 2012-11-09T04:58:58.440 回答