How to make a Json_decode from a json file

Asked

Viewed 66 times

1

Hello,

I am currently storing data in json format in a fopen file.

$json = fopen("$root/apil/Controllers/json/" . $this->getX_id() . ".json", "w+"); $customers_results = $customers->fetchAll(PDO::FETCH_OBJ); foreach ($customers_results as $customer) { array_push($file_content , $customer->x_id); } fwrite($json, json_encode($file_content)); fclose($json);

So far all right the file is being stored in JSON format correctly: elementos já inseridos no arquivos

And as expected I use this same file in another class, however , when performing a json_decode of the $file variable that "comes" from fopen me is returned the following error:

Warning: json_decode() expects parameter 1 to be string, resource given in ...

The code I use to collect the data from the file and later perform a json_decode is this:

$root = $_SERVER['DOCUMENT_ROOT']; $x_id = $this->x_id(); $y_id = $this->y_id(); $file = fopen("$root/apil/Controllers/json/" . $y_id . ".json", "w+"); $aux = json_decode($file); fclose($file); ...

It is worth mentioning , that after searching for solutions in Forums also tried to use the json_decode as follows $aux = json_decode(json_encode($file)); in this case no error is returned to me , however, when using the json_last_error() me is returned the error 4 that according to the documentation means JSON_ERROR_SYNTAX , is worth warning that the variable $y_id also has the correct content which in case is the name of my file.

Thank you in advance if anyone can help me with this problem.

  • 1

    In the error it says that the type of the $file variable is Resource and not string, confirm this by doing an echo gettype($file) to find the type of the $file variable, if it is Resource and not string, try somehow to convert to string

  • Thanks for the tip Douglas, really the file was of type Resource and to work with this type of data is a little laborious. As in the case I am using the query-only file I ended up using the following instruction $linha = file_get_contents("$root/apil/Controllers/json/" . $x_id . ".json");

  • Very good! Success brother!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.