2017-10-07 3 views
0

그래서 JSON 파일을 가져오고 PokeAPI 호출을 JSON으로 저장하기 위해 Codeigniter에서 직접 헬퍼를 만들기로 결정했습니다.json_decode() - 내가 뭘 잘못하고 있니?

내가 좋은 작품을 만든 저장 JSON 방법 다음해서 getJSON 기능이 매우 무작위로 작동하지만

if (! function_exists('saveJson')) { 
    function saveJson($file, $data) { 
     $fp = fopen($file, 'w'); 
     fwrite($fp, json_encode($data)); 
     fclose($fp); 
    } 
} 

. 특정 파일을 가져 오는 데는 작동하지만 다른 파일에서는이 오류가 발생합니다. 메시지 : json_decode()는 매개 변수 1이 주어진 문자열 일 것으로 예상합니다.

해서 getJSON 기능 (모든 JSON 파일이 같은 형식입니다) :

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\"}],... 
+0

JSON 파일의 내용을 게시 할 수 있습니까? – barni

+1

'$ data'가 이미 json으로 디코딩되었습니다. 왜 다시 디코딩하려고합니까? '$ data = json_decode ($ json, true); $ pkm = json_decode ($ data, true);'- 첫 번째 json_decode가 문자열을 반환하는 경우에만 작동합니다. 어쨌든 디코딩하는 데별로 의미가 없나요? – ccKep

+0

일반적으로, save 메소드에서 수행하는 모든 조치는로드 메소드에서도 마찬가지입니다. 당신은 당신의 저장 메소드에서 ** 하나 ** 인코딩을하고,로드 메소드에서 ** 하나의 ** 디코딩을합니다. – ccKep

답변

1

내가 @ccKep에 문제 덕분에 해결했습니다. 나의해서 getJSON 함수에서 두 번째 json_decode를 제거한 다음

if (! function_exists('saveJson')) { 
    function saveJson($file, $data) { 
     $fp = fopen($file, 'w'); 
     fwrite($fp, $data); 
     fclose($fp); 
    } 
} 

을 그리고 :

if (! function_exists('getJson')) { 
    function getJson($file) { 
     $json = file_get_contents($file); 
     $data = json_decode($json, true); 
     return $data; 
    } 
} 

이 내가 수신 된 오류를 수정

나는 그렇게처럼 내 saveJSON 기능에서 JSON 인코딩을 제거했습니다.

관련 문제