Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read JSON file inside CodeIgniter Controller

I can't read my json file inside codeigniter controller, it returns an error.

My code:

$curYear = date("Y");
$string = file_get_contents(base_url("assets/data/".$curYear."_cal.json"));

Error Message return by my controller trying to read json file using:

file_get_contents(//localhost/EBR_Labeling/assets/data/2018_cal.json): failed to open stream: No such file or directory


Solved

Using this syntax:

file_get_contents("./assets/data/".$curYear."_cal.json")
like image 901
Raniel Garcia Avatar asked Oct 24 '25 16:10

Raniel Garcia


2 Answers

Please use this code --

<?php

$json = file_get_contents(FILE_PATH);
$obj  = json_decode($json);
echo '<pre>' . print_r($obj) . '</pre>';

?>

And let me know If you need any other help.

Thanks

like image 162
Sorav Garg Avatar answered Oct 26 '25 07:10

Sorav Garg


We can simply store all json in views folder and can access it directly as follow:-

<?php 
    $countries = $this->load->view('countries.json', '', true) //this will load countries.json
    $countries = json_decode($countries);
?>

Points to be noted : -

  1. $this->load->view('countries') is same as writing $this->load->view('countries.php') And this loads the view in browser and doesn't store it in variable. When we want some another type of file to be loaded, then we can simply change the extension.
  2. $this->load->view('countries', $data, true); Passing third parameter as true allows us to store the view in variable. If we don't want to pass second parameter then we can pass empty string as $this->load->view('countries', '', true);
like image 40
Jayant kumar Avatar answered Oct 26 '25 06:10

Jayant kumar