我正在研究从Google Playstore中抓取结构化数据并将其保存在数据库中的应用程序。我得到了所有的结构化数据。我正在尝试复制itemprop="image"
url并将图像保存到我的服务器。
我已经尝试了很多事情,但没有工作,因为文件没有扩展名。下面的代码可以工作,但是要么生成无效的文件,要么创建一个零字节的文件。
我试图复制的示例url
https://lh3.googleusercontent.com/IYZe0LQOUKXpEYOyVOYYMJo4NnqBnDYkkhDgfYTgDCpuxAyy1ziBkOn0b6_LZxQ3qI4=w300-rw
我正在使用的PHP代码
function getimg($url) {
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'php';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $useragent);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER,false);
// curl_setopt($process, CURLOPT_SSL_VERIFYPEER,0);
$return = curl_exec($process);
curl_close($process);
return $return;
}
$image="https://lh3.googleusercontent.com/IYZe0LQOUKXpEYOyVOYYMJo4NnqBnDYkkhDgfYTgDCpuxAyy1ziBkOn0b6_LZxQ3qI4=w300-rw";
$upload_dir = wp_upload_dir();
$length= strlen($image);
$new_string = substr($image,0,$length-8);
$imagename= basename($new_string);
$image2 = getimg($imgurl);
$new_image_path = file_put_contents($upload_dir['basedir'].'/custom-temp/'.$imagename,$image2);
您的代码中有几个错误,例如$useragent
未一致命名和$imgurl
未定义。考虑在调试时打开PHP中的错误,以便可以捕获这些错误。
我可以让你的代码像这样工作(只是改变路径回到wp_upload_dir()
):
function getimg($url) {
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$gim = 'php';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
// curl_setopt($process, CURLOPT_USERAGENT, $useragent);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER,false);
// curl_setopt($process, CURLOPT_SSL_VERIFYPEER,0);
$return = curl_exec($process);
curl_close($process);
return $return;
}
$image="https://lh3.googleusercontent.com/IYZe0LQOUKXpEYOyVOYYMJo4NnqBnDYkkhDgfYTgDCpuxAyy1ziBkOn0b6_LZxQ3qI4=w300-rw";
$upload_dir = "/home/laurent/test/upload";
$length= strlen($image);
$new_string = substr($image,0,$length-8);
$imagename= basename($new_string);
$image2 = getimg($image);
$new_image_path = file_put_contents($upload_dir.'/'.$imagename,$image2);