Sunday, December 4, 2022

[FIXED] How to make file .json with codeigniter?

Issue

This is my json encode in my controller:

public function loaddata(){
    $sql = $this->db->query('select * from e_alat_angkutan')->result();

    return json_encode($sql);

}

how to make file .json ? please help


Solution

In the controller __construct() method load the file helper:

public function __construct()
{
    parent::__construct();
    $this->load->helper('file');
}

And then echo it with second param to TRUE:

public function loaddata(){
    $sql = $this->db->query('select * from e_alat_angkutan')->result();

    echo json_encode($sql,TRUE);
}

As points this answer Write to JSON file using CodeIgniter:

//If the json is correct, you can then write the file and load the view

// $fp = fopen('./data.json', 'w');
// fwrite($fp, json_encode($sql));

// if ( ! write_file('./data.json', $arr))
// {
//     echo 'Unable to write the file';
// }
// else
// {
//     echo 'file written';
// }   

Hope it helps!



Answered By - JP. Aulet
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.