lundi 3 octobre 2016

Add product images automatically with CURL php

I've been trying to add images with curl to all my products without success. My images are located in http://ift.tt/2cMKW39 (i've uploaded them here).

For product each product i (id = ID_i, ref = REF_i) the image is called REF_i.jpg

This is what I've been trying to do:

function image($id, $ref){
   // change the local path where image has been downloaded (I run script at the folder before prestashop)
    $img_path = '/prestashop/img/ProductImages/{$ref}.jpg';


define('PS_SHOP_PATH', 'http://ift.tt/2dD96TI');
//image will be associated with product id $id
$url = PS_SHOP_PATH. '/api/images/products/'.$id;


$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, PS_WS_AUTH_KEY.'SOMEKEY');
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image'=> new CurlFile($img_path)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


if(curl_exec($ch) === false)
{
  echo "<br><br>Error : ".curl_error($ch)."<br>";
}
else { echo '<br><br> Image added'; }
curl_close($ch);


}


ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
define('PS_SHOP_PATH', 'http://ift.tt/2dD96TI');
define('PS_WS_AUTH_KEY', 'SOMEKEY');
define('DEBUG', 'false');


require_once('PSWebServiceLibrary.php');
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);


$opt['resource'] = 'products';
$opt['display'] = 'full';
try{
    $xml = $webService->get($opt);
}catch( PrestaShopWebserviceException $ex ){
    $trace = $ex->getTrace(); // Retrieve all information on the error
     $errorCode = $trace[ 0 ][ 'args' ][ 0 ]; // Retrieve the error code
     if ( $errorCode == 401 )
           echo 'Bad auth key';
     else
           echo 'Other error :
    }
    foreach($products as $product)    {
        image($product->id, $product->reference)
    }

?>

Could you help me figure out why it doesn't work?

Thanks, Carolina




Aucun commentaire:

Enregistrer un commentaire