php 从URL抓取图像

w6lpcovy  于 2023-11-16  发布在  PHP
关注(0)|答案(2)|浏览(103)

我如何从亚马逊上抓取一张格式如下的图片:
https://platform.s3.us-west-2.amazonaws.com/listing/31767-84007-dwBVIaLkhsGzpK4sfxaS-T07Gd-EXAd78l8lsJpeuYM-618cf68ce2350
我从预订引擎API获得此数据,没有其他方法可以获得不同的结果。
我使用WordPress和“media_sideload_image”不接受它作为一个有效的URL。

xqnpmsa8

xqnpmsa81#

同样的问题对我来说,我公开了文件,我能够以https://metapyxl.s3.amazonaws.com/images/1696425186798_1.png的身份访问我的图像
因此,您需要在S3 bucket上公开您的图像。
我附加的图像更新S3桶的权限。
Allow public access
Allow Bucket policy

mm9b1k5b

mm9b1k5b2#

require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

function upload_image_from_url($image_url) {
    // Check if the URL is valid
    if (filter_var($image_url, FILTER_VALIDATE_URL)) {
        // Get the file type
        $file_type = wp_check_filetype(basename($image_url), null);

        // Prepare an array of data for the attachment
        $attachment = array(
            'post_title'     => sanitize_file_name(basename($image_url)),
            'post_mime_type' => $file_type['type'],
        );

        // Try to upload the image
        $attachment_id = media_sideload_image($image_url, 0, null, 'id');

        if (!is_wp_error($attachment_id)) {
            // The image was successfully uploaded, and $attachment_id contains the attachment ID.
            return $attachment_id;
        } else {
            // An error occurred during the upload.
            return false;
        }
    }

    return false;
}

// Example usage:
$image_url = 'https://metapyxl.s3.amazonaws.com/images/1696425186798_1.png';
$attachment_id = upload_image_from_url($image_url);

if ($attachment_id) {
    // The image was uploaded successfully. You can use $attachment_id as needed.
} else {
    // There was an error uploading the image.
}

字符串

相关问题