2

I have a response from my code which looks like this

Controller

   $results = $response 
   echo $result->item;
   exit;

Response

{"item":"Samsung A","location":"Hamburg Avenue 5920"}

I want to get only item from the response..How do i achieve this ? The response is json encoded

RoboPHP
  • 410
  • 4
  • 12
  • 1
    Is there a typo in the controller code you posted? You've got both `$results` and `$result` variables. And if you're calling `exit` after echoing from the wrong variable, are you currently seeing any output at all? It's not very clear what the code is currently doing. – iainn Mar 11 '20 at 12:35

3 Answers3

2

You need to convert json to object, and after that you can get the element:

$respObject = json_decode($response);
echo $respObject->item;
exit;
Vasyl Zhuryk
  • 1,228
  • 10
  • 23
1

Use json_decode the result will converted into array

$results = json_decode($response); 
print_r( $results);
exit;
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Boominathan Elango
  • 1,156
  • 2
  • 7
  • 20
1

json_decode function will helps.

$json_data = '{"item":"Samsung A","location":"Hamburg Avenue 5920"}';
$result = json_decode($json_data); 
echo $result->item;
ashokan
  • 70
  • 5