Home > Mobile >  How to return Json data array with PHP/Laravel?
How to return Json data array with PHP/Laravel?

Time:10-14

I'm devoloping an api with Laravel and I have to get the data of a json file in a url, this is my code:

public function index(){
    $json_file=file_get_contents("url that I'm using");
    $json_str = json_decode($json_file);
    
    echo $json_str;
}

The JSON file:

{
  "success":true,
  "clients": [
      [
       "name": "Tyler Durden",
       "job": "leader of the ..."
      ],
  ]
}

But when I access my route that call the index() I get this error:

Object of class stdClass could not be converted to string

I want to get any pair of clients and save them, can someone help me?

CodePudding user response:

You can't print an object using echo, to print an object you can use

print_r($json_str);
var_dump($json_str);

In your case you just need a return statement

return $json_str;

In Laravel you can also, do this

return response()->json($json_str);

CodePudding user response:

you are trying to print a json instead of a string. echo will only print a string.

  • Related