php - 将JSON数据解析到数据库时出错
我正试图用从API中获得的价格更新所有产品。现在我在运行脚本时得到了这个错误。
Array ( [update] => Array ( [0] => Array ( [id] => 0 [error] => Array ( [code] => woocommerce_rest_product_invalid_id [message] => Invalid ID. [data] => Array ( [status] => 400 ) ) ) ) )
我哪里出错了?我知道它说ID无效,但我真的不知道如何在不处理每个ID的情况下迭代产品。
<?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;
$woocommerce = new Client(
'http://exemple.com',
'ck_xxxxxxxxxxx',
'cs_xxxxxxxxxxx',
[
'wp_api' => true,
'version' => 'wc/v2',
// 'query_string_auth' => true
]
);
function parse_json( $file ) {
$json = json_decode( file_get_contents( $file ), true );
if ( is_array( $json ) && !empty( $json ) ) :
return $json;
else :
die( 'An error occurred while parsing ' . $file . ' file.' );
endif;
}
$url = 'https://username:[email protected]/apis/v1.0/xxxxxxxx';
$json = parse_json($url);
foreach ($json as $product){
$data = [
'update' => [
[
'id' => (int)$product['id'],
'regular_price' => $product['regular_price']
]
]
];
}
print_r($woocommerce->post('products/batch', $data));
?>
这是我试图从API中获取价格的数据结构。
[
{
"id": "595",
"type": "simple",
"parent_product_id": "",
"name": "Product 1",
"description": "Descrição",
"regular_price": "26.78",
"manage_stock": "1",
"stock": "5",
"weight": "0",
"attribute_name": "",
"attribute_value": "",
"has_variations": "",
"image": "site.com/imagem1.png",
"sku": "10010"
},
{
"id": "596",
"type": "simple",
"parent_product_id": "",
"name": "Product 2",
"description": "Descrição",
"regular_price": "0",
"manage_stock": "0",
"stock": "0",
"weight": "0",
"attribute_name": "",
"attribute_value": "",
"has_variations": "",
"image": "site.com/imagem2.png",
"sku": "11010"
},
(...)
]
【回答】:
它是你的 $url = 'https://username:[email protected]/apis/v1.0/xxxxxxxx';
使用。
$user = 'username';
$pass = 'password'
$url = 'http://apiservice.com/apis/v1.0/xxxxx'
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("$user:$pass")
)
));
$data = file_get_contents($url, false, $context);
$json_new = json_decode($data, true);