I’m pretty sure I’m missing something simple, anyway, I have tried for the past three hours to JSON encode some query results, something I do it quite often with code igniter, however, it just doesn’t work, and I have no idea why.
I’m using CodeIgniter (latest version), PHP5.
My three files.
material_model MODEL
public function get_types(){
return $this->db->query("SELECT * FROM material_types ORDER BY type_id")->result_array();
} // end function get_types
public function get_material($name){
return $this->db->query("SELECT T.name as 'type', M.* FROM material M, material_types T WHERE T.type_id = M.type_id and T.name = '".$name."' ORDER BY M.type_id and M.order")->result_array();
} // end function get_material_all
material Controller
public function get_all(){
$json['response'] = array('types' => array());
$json['response']['types'] = $this->material_model->get_types();
foreach ($json['response']['types'] as $item){
$name = $item['name'];
$json['response'][$name] = $this->material_model->get_material($name);
}
$this->load->view('response', $json);
}
response VIEW
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
echo json_encode($response);
The results -> http://goethedev.com/iib_ci/index.php/material/get_all/
What I use to validate the JSON pages -> http://jsonformatter.curiousconcept.com/
I’m displaying the whole results up there, I already tried to narrow it down for testing purposes to just row_array, only a couple of fields from table material_types, but no luck, this is also a new server I’m working on, that’s unlikely the problem, but I thought it was worth mentioning.
Thanks.
The json being returned from the URL you provided is being displayed for me just fine, and it validates as well. Either you’ve fixed it since posting, or perhaps you need to clear your browser cache?
UPDATE
The code was validating just fine when I copy/pasted it to the validator you provided, but using the URL it fails. That tells me that there’s something extra/wrong that’s coming through that isn’t included when copy/pasting from the browser.
To identify it I ran
curl http://goethedev.com/iib_ci/index.php/material/get_all/ | lessand here’s what I got:<U+FEFF>represents a byte order mark. Since there are three of them, it appears three files in your CI project have the byte order mark included. I recommend, as does PSR2, always disabling the byte order mark in your PHP code. Your editor should have an option to remove/disable them. Once you do that, you should be able to parse the json.