Facebook Marketing API: Upload Image to library provided a URL

908 views Asked by At

I am new to the Facebook Marketing API and what I am working on is to upload an image to my FB Marketing library.

Right now, I can successfully upload an image to the FB Marketing but unfortunately I cannot see if there is a way to upload an image from a URL.

Has anyone had any previous experience with that ?

Code sample:

     Api::init(getenv('FACEBOOK_APP_ID'), getenv('FACEBOOK_APP_SECRET'), getenv('FACEBOOK_APP_TOKEN'));


    /**
     * {@inheritdoc}
     */
    public function testFunc()
    {
        $adAccountId = getenv('FACEBOOK_APP_ACCOUNT_ID');
        $account = new AdAccount();
        $account->{AdAccountFields::ID} = $adAccountId;

        $image = new AdImage(null, "act_{$account->id}");

        $image->{AdImageFields::FILENAME} = getenv('FACEBOOK_APP_MARKETING_PATH').'fbTestImage.png';
        $image->create();

        $this->line('Image Hash: '.$image->{AdImageFields::HASH}.PHP_EOL);
    }
1

There are 1 answers

0
Bill Burey On

You have to use PHP to pull the image from the URL write it to a temporary file, upload. that then delete the temporary file when complete (Not ideal but a solution). The the Node.js Marketing API you can supply the content rather than the filename to the API which is nice.

However a possible solution for now.

$url = "https://www.sample/image.png";

// Create output file name
$arr = explode("/",$url);
$img_file = dir(__FILE__).'/tmp_'.$arr[count($arr)-1];
// Load File contents from URL
$data = file_get_contents($url);
// Write Temporary File
$fp = fopen($img_file,"w");
fwrite($fp,$data);
fclose($fp);

// Then Push the temp file to Facebook
// Rest of FB Code...
$image->{AdImageFields::FILENAME} = $img_file;

// Wait for the Upload to complete then delete the temp file
unlink($img_file);