如何在prestashop webservice中获取图像ID

时间:2016-09-12 06:29:58

标签: php web-services prestashop prestashop-1.6

我想用产品组合映射图像。 下面的代码可以成功添加图片,但它不会在返回结果中给我图像ID。

代码:

$img_path = DIR_PATH_CONFIG.'/'.$this->filename.'_images/'. $imagename;
        //image will be associated with product id 4
        $url = PS_SHOP_PATH. '/api/images/products/'.$id_product;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        //curl_setopt($ch, CURLOPT_PUT, true); To edit a picture
        curl_setopt($ch, CURLOPT_USERPWD, PS_WS_AUTH_KEY.':');
        curl_setopt($ch, CURLOPT_POSTFIELDS, array('image'=>"@".$img_path.";type=image/jpeg"));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        if($result === false)
        {
        $var = false;
        echo "<br><br>Error : ".curl_error($result)."<br>"; }
        else 
        {
        echo '<br><br> Image added'; 
        //$xml = simplexml_load_string($result);
        //$imageId = $xml->image->id;
        unlink($img_path);
        $var = true;
        }

任何有想法的人都可以让我知道..?

1 个答案:

答案 0 :(得分:1)

将图像添加到没有图像的产品(在/ api / images / products / {ID}中找不到任何条目)。关键是创建一个新的CurlFile,而不是仅仅将图像的二进制文件发送回PS WS。您可以使用以下功能:

/**
* Function that creates a new Product Feature Value and returns its newly created id
* @param product_id = the id of the product for which the image should be uploaded
* @param image_name = the String containing the name of the downloaded image (which will be found in /img)
* @return the ID of the newly inserted image
*/
function addNewImage( $product_id, $image_name  ) {
    $url = PS_SHOP_PATH . '/api/images/products/' . $product_id;
    $image_path = 'img/'. $image_name;
    $key = PS_WS_AUTH_KEY;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:multipart/form-data','Expect:'));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_USERPWD, $key.':');
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => new CurlFile($image_path)));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}