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
  • 400
  • 3
  • 10
  • 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,140
  • 7
  • 22
1

Use json_decode the result will converted into array

$results = json_decode($response); 
print_r( $results);
exit;
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Boominathan Elango
  • 1,068
  • 1
  • 6
  • 19
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