php - How can I encode a cURL response to be a JSON object? -
i'm trying post php controller using jquery ajax. want controller retrieve data api , return data ajax function.
here javascript:
$(function() {      $.ajax({         type: 'post',         url: '/mycontroller/myaction/',         success: function(data) {                    console.log(data);         }     });  });   here action in controller:
public function myaction() {      $ch = curl_init();      $endpoint = 'https://endpointfortheapi.com';      curl_setopt($ch, curlopt_url, $endpoint);      curl_setopt($ch, curlopt_returntransfer, true);     curl_setopt($ch, curlopt_httpheader, array(         'content-type: application/json; charset=utf-8'     ));      $response = curl_exec($ch);      $response = json_encode($response);      echo $response;      curl_close($ch); }   this seems work, however, when use json_encode() array returned escaped string, not json object. when console.log(data) in ajax request, see string this:
"[{\"firstproperty\":\"firstvalue\",\"secondproperty\":\"secondvalue\"}]"   how can encode response array actual json object?
so you’re doing this:
$response = curl_exec($ch);     $response = json_encode($response);   unclear returned data https://endpointfortheapi.com, seems me taking source json response & double-encoding response when json_encode again.
if send plain string json_encode instead of object or array—it escape seeing. remove or comment out line & see if clears things up.
also, should setting proper json headers in php before echo. based on mention above & headers refactor php code this:
public function myaction() {      $ch = curl_init();      $endpoint = 'https://endpointfortheapi.com';      curl_setopt($ch, curlopt_url, $endpoint);      curl_setopt($ch, curlopt_returntransfer, true);      $response = curl_exec($ch);     // $response = json_encode($response);      // header('x-json: (' . $response. ')');     header('content-type: application/json');     echo $response;      curl_close($ch);  }   i commented out x-json header since there controversy surrounding use of custom header used applications automatically evaluate json data if using the prototype javascript framework. not worth hassle if not using prototype , don’t care such things.
Comments
Post a Comment