简体   繁体   English

在 Json Curl 上使用生成的 PHP 字符串获取“无效的关键字符”

[英]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.因此,我正在尝试使用 php 与项目的 curl 进行通信,并使用 POST 方法从我的数据库发送数据。

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...如果我将生成的 json 复制并粘贴到 JSONLint,则表明 json 是有效的...

Any Tips on how to solve this?有关如何解决此问题的任何提示?

You just don't build JSON by hand in PHP.您只是不要在 PHP 中手动构建 JSON

You first build your data structure and THEN you json_encode() the whole thing...你首先建立你的数据结构,然后json_encode()整个事情......

$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.) . json_encode()为您处理一切(转义等) It also has some options - for that see the manual .它也有一些选项——参见手册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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