You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PrestaShop 8 API添加产品报500错误:数组偏移访问空值

PrestaShop Web Service API添加产品触发HTTP 500错误的解决办法

问题描述

通过PrestaShop Web Service API添加产品时触发HTTP 500内部服务器错误,错误详情:

[PHP Warning #2] Trying to access array offset on value of type null(对应路径...\prestashop\classes\Product.php,第7094行)

用户使用代码如下:

$url = 'http:///localhost/prestashop/';
$key = 'ST5TVKFHV685W4MWN9BYF2HXG3PB19FB';
$debug = true;
$webService = new PrestaShopWebservice($url, $key, $debug);

$blankXml = $webService->get(['url' => $url . 'api/products?schema=blank']);

$productXML = $blankXml->product->children();

$productXML->price = 100;
$productXML->id_category_default = 3; // 3 is an id of an existing parent category
$productXML->position_in_category = 1;

$createdXml = $webService->add([
            'resource' => 'products',
            'postXml' => $blankXml->asXML(),
        ]);

用户已尝试:不填写分类ID、补充state/description等属性,但问题未解决。

错误原因

错误根源是产品分类关联数据不完整:仅设置id_category_default不足以让PrestaShop系统正确处理分类关联逻辑,内部处理时会因缺失associations下的分类节点,导致对应数组变量为null,触发偏移量访问警告并引发500错误。

解决方案

核心修正:补充分类关联节点

必须在XML中添加associations->categories节点,明确指定产品所属分类(至少包含默认分类),同时修正URL的格式错误。修正后代码如下:

$url = 'http://localhost/prestashop/'; // 修正多斜杠的URL错误
$key = 'ST5TVKFHV685W4MWN9BYF2HXG3PB19FB';
$debug = true;
$webService = new PrestaShopWebservice($url, $key, $debug);

$blankXml = $webService->get(['url' => $url . 'api/products?schema=blank']);

// 直接操作product节点,避免children()丢失层级结构
$productXML = $blankXml->product;
$productXML->price = 100;
$productXML->id_category_default = 3;
$productXML->position_in_category = 1;

// 添加分类关联节点
$associations = $productXML->addChild('associations');
$categories = $associations->addChild('categories');
$category = $categories->addChild('category');
$category->addChild('id', 3); // 与默认分类ID保持一致

$createdXml = $webService->add([
    'resource' => 'products',
    'postXml' => $blankXml->asXML(),
]);

额外注意事项

  1. 确认分类ID3是系统中存在的有效分类ID(父分类或子分类均可)
  2. 若问题仍存在,可直接查看Product.php第7094行代码,确认具体是哪个数组变量为null,进一步定位数据缺失项
  3. 确保PrestaShop Web Service权限已开启产品添加权限

内容的提问来源于stack exchange,提问作者hicham CHERQI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:37:35