webService php + json

1

Hello

I would like help with integrating with webService via url, for example:

$list_result = '{"titulo": '. 
  '[{"id":$id_primary}'.
']}';

$json = json_encode($list_result);

//echo $json;

//API Url
$url = 'https://local-que-devo-enviar.com.br/arquivo';



$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(

    'Content-Type: application/json',
    'Content-Length: ' . strlen($json))
);


//retorno   
$jsonRet = json_decode(curl_exec($ch)); 

var_dump($jsonRet);
  • I would like help to understand if I am mounting the data array correctly, how do I get a return and if the code stays that way. Because I'm not getting return from webservice ...
asked by anonymous 07.11.2017 / 16:41

2 answers

1

You are in the path, but you have deviated at the moment of creating the JSON that you are sending ..

To encode something in JSON with PHP you must pass an array as a parameter. Change the first few lines for this, test and say the result in the comments to refine our answer:

$list_result = array(
    'titulo' => array(
        array(
            'id' => $id_primary,
        ),
    ),
);

$json = json_encode($list_result);

Ah! And, add this to your request settings to see more data about the server response:

curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

And, you have to close the curl at the end and notice that I have removed the json_decode function at that time just to check the response from the server that has header:

$jsonRet = curl_exec($ch); 
curl_close($ch);
var_dump($jsonRet);
    
07.11.2017 / 17:44
0

I realized that I need a group and a subgroup in the array .. how would it look like ...
    {
   "test": 9999,    "test": 99999,    "test": "LINDL0001",    "items": [
      {
         "item1Test1": {             "item1": "123",             "item2": 11,             "item3": "22/09/2006",
         },          "item2DoTest1": {             "a": 123,             "b": "2 x",             "c": 3,             "d": "s 44",          },

    
07.11.2017 / 18:46