0
所以我决定在Codeigniter中创建自己的帮手来获取JSON文件并将PokeAPI调用保存为JSON。json_decode() - 我做错了什么?
的保存方法JSON我创作的作品罚款:
if (! function_exists('saveJson')) {
function saveJson($file, $data) {
$fp = fopen($file, 'w');
fwrite($fp, json_encode($data));
fclose($fp);
}
}
然而,功能的getJSON工作非常随机。它适用于获取某些文件,但其他人会抛出此错误:消息:json_decode()期望参数1是字符串,给定的数组。(所有的JSON文件是相同的格式)
的getJSON功能:
if (! function_exists('getJson')) {
function getJson($file) {
$json = file_get_contents($file);
$data = json_decode($json, true);
$pkm = json_decode($data, true);
return $pkm;
}
}
其奇,我必须将JSON两次解码或可我不能在我的意见访问阵列。
我的模型和控制器就这一问题进一步深入: 型号功能例如:
function getPokemonById($id) {
$filepath = './assets/jsonsaves/pokemoncalls/'. $id. '.json';
if(file_exists($filepath)) {
$pokemonByIdData = getJson($filepath);
} else {
$url = $this->pokemonApiAddress.$id.'/';
$response = Requests::get($url);
saveJson($filepath, $response);
$pokemonByIdData = json_decode($response->body, true);
}
return $pokemonByIdData;
}
控制器功能例如:
public function viewPokemon($id) {
$singlePokemon['pokemon'] = $this->pokemon_model->getPokemonById($id);
$singlePokemon['species'] = $this->pokemon_model->getPokemonSpecies($id);
$data['thepokemon'] = $this->pokemon_model->getAllPokemon();
$this->load->view('template/header', $data);
$this->load->view('pokemonpage', $singlePokemon);
$this->load->view('template/footer');
}
所以在我的JSON文件中的一些变化。在一个JSON文件不起作用它,开头:
{"body":"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/142\\\/\",\"name\":\"aerodactyl\"}],...
但是这一个工程:
"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/6\\\/\",\"name\":\"charizard\"}],...
你可以发布你的JSON文件内容的例子吗? – barni
'$ data'已经解码json,你为什么要重新解码它? '$ data = json_decode($ json,true); $ pkm = json_decode($ data,true);' - 这只会在第一个json_decode返回一个字符串时才起作用,而这对解码无济于事。 – ccKep
作为一般经验法则:您在保存方法中执行的每个操作也可以在您的加载方法中进行,反之亦然。在保存方法中,您可以** ** **编码,您可以** ** **在您的加载方法中进行解码。 – ccKep