简体   繁体   中英

Getting "Invalid Key Character" With generated PHP string on Json Curl

So, i'm trying to communicate with a curl for a project using php, and send data from my database with the POST method.

but i'm getting the "Invalid Key Character" error, and i really don't know what else to do to fix this...

The code:

<?php
require_once('autoload.php');
require_once('vendor/autoload.php');

$conexao = new Conexao();

$produtos = $conexao->select('produto', '*', 'LIMIT 1');

foreach ($produtos as $produto) {
    try {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, "url");
        $headers = array();
        $headers[] = "Content-Type: application/json";
        $headers[] = "X-Api-Key: key";
        $headers[] = "X-App-Key: key";
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($curl, CURLOPT_HEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_POST, TRUE);

        $status = 1;

        if ($produto['status'] == 1){ 
            $status = 0;
        }

        $valores = '
        {
            "product":{
                "name":"'. trim($produto['descricao']) .'",
                "sku":"'. trim($produto['cod_est']) .'",
                "description":"'. trim($produto['obs']) .'",
                "price":'. $produto['valor_vend'] .',
                "saleprice":'. $produto['vl_promo'] .',
                "categories": [
                    "'. trim($produto['ender3']) .'"
                ],
                "properties": [],
                "related_products": [],
                "special_options": [],
                "slug":"'. str_replace(' ', '-', trim($produto['descricao'])) .'",
                "excerpt":"'. trim($produto['descricao']) .'",
                "factory_price":'. $produto['ult_custo'] .',
                "installments": 1,
                "shippable":0,
                "fixed_quantity": 999,
                "gtin_code":"'. trim($produto['cod_fabr']) .'",
                "ncm_code":"'. trim($produto['cod_ncm']). '",
                "track_stock": 0,
                "enabled":' . $status . ',
                "video": "",
                "weight":"' . $produto['peso_brut']. '",
                "height": "' . $produto['espessura'] . '",
                "width": "' . $produto['largura'] . '",
                "depth": "' . $produto['compriment'] . '",
                "meta": "",
                "seo_title": "",
                "seo_description":"'. trim($produto['descricao']) . '",
                "seo_keywords":"'. str_replace(' ',',',strtolower(trim($produto['descricao']))) .'"
            }
        }';

        curl_setopt($curl, CURLOPT_POSTFIELDS, $valores);

        $response = curl_exec($curl);
        curl_close($curl);

        print_r($response);
    }

    catch (Exception $e){
        echo 'Ocorreu um Erro: ' . $e;
    }

}

The error:

HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 Content-Length: 263 Connection: keep-alive Cache-Control: max-age=1, public Date: Wed, 27 Dec 2017 19:09:30 GMT Expires: Wed, 27 Dec 2017 19:09:31 GMT Server: Apache Vary: Accept-Encoding X-Cache: Miss from cloudfront Via: 1.1 f2e2a7eca4778c8776461616fad77017.cloudfront.net (CloudFront) X-Amz-Cf-Id: urR4k92zkT2PCfimpCNAf5-uBmUi46nvHM6J-aWVZ8OxDYZUPteEWg== Disallowed Key Characters. "\r\n\t\t{\r\n\t\t\t\"product\":{\r\n\t\t\t\t\"name\":\"PH_CAMISA_GOLA_V_BR_12\",\r\n\t\t\t\t\"sku\":\"2129246\",\r\n\t\t\t\t\"description\":\"\",\r\n\t\t\t\t\"price\":49_000,\r\n\t\t\t\t\"saleprice\":0_000,\r\n\t\t\t\t\"categories\":_"

if i copy the generated json and paste to JSONLint, it shows that the json is valid...

Any Tips on how to solve this?

You just don't build JSON by hand in PHP.

You first build your data structure and THEN you json_encode() the whole thing...

$valores = [
    "product" => [
        "name" => trim($produto['descricao']),
        "sku" => trim($produto['cod_est']),
        "description" => trim($produto['obs']),
        "price" => $produto['valor_vend'],
        "saleprice" => $produto['vl_promo'],
        "categories" => [
            trim($produto['ender3']) // I'm not so sure here...
        ],
        "properties" => [],
        ...
        ...
        ...
    ]
];
// $valores is an array containing your data.

$encoded = json_encode($valores);
// $encoded is a string containing encoded JSON.

json_encode() handles everything for you (escaping, etc.) . It also has some options - for that see the manual .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM