Home > Software engineering >  API JSON output Format
API JSON output Format

Time:02-19

I have this code

<?php
$id = $_POST['id'];
$nume = $_POST['nume'];
$rrp = $_POST['rrp'];
$pret = $_POST['pret'];
$stoc = $_POST['stoc'];
$url = $_POST['url'];
$url1 = $_POST['url1'];
$url2 = $_POST['url2'];
$url3 = $_POST['url3'];

$username = "[email protected]";
$password = "aaa";

$apiUrl = "https://partners.services.aaaa.eu/v1/mkpApi/product/save";

$auth    = base64_encode($username . ":" . $password);
$headers = [
     "Authorization: Basic " . $auth,
     "Content-Type: application/x-www-form-urlencoded",
];

$payload[] = [
     "id"              => $id,
     "locale"          => "RO",
     "hidden"          => 0,
     "currency"        => "RON",
     "brand"        => "Decorepublic",
     "name" => $nume,
     "category_id"  => 10008,
     "status"        => "1",
     "vat" => "0", 
     "stock"           => [[
         "warehouse_id" => 1,
         "value"        => $stoc,
     ]],
     "sale_price"      => $pret,
     "rrp" => $rrp,
     "description"     => $nume,
     
     "images" => [
         ["url"   => $url],
         ["url"   => $url1],
         ["url"   => $url2],
         ["url"   => $url3],
     ],
];


$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(["data" => json_encode($payload)]));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result   = curl_exec($ch);
$response = json_decode($result, true);

print_r($response);

//echo '<br><br>';

echo json_encode($payload);

print $stoc;
?>

At output i have

status":"1","vat":"0","stock":[{"warehouse_id":1,"value":"200"}]

I need to have value without "" like this:

status":"1","vat":"0","stock":[{"warehouse_id":1,"value":200}],"

I trie to use print $stoc, but it returns value 1.

I tried get function but it doesn't work. Any idea?

CodePudding user response:

If you've got a string in $stoc and you need to convert it to an integer before you encode it as JSON, then you can use intval.

"value" => intval($stoc)

Demo: http://sandbox.onlinephpfunctions.com/code/8b1ed16c28bfbc47f501981f2bf03f7b1bb9ce45

  • Related