2011-12-08 1 views
0

PHP를 처음 사용했습니다. json_encode를 사용하여 배열을 json 데이터로 변환하고 다른 파일의 json_decode를 사용하여 디코딩합니다. 그러나 구문 오류로 json 오류가 나타납니다. 다음과 같이json_encode 및 json_decode 사용법

내 코드는 다음과 같습니다

파일 1 :

$result = get_data_array(); 

exit(json_encode($result)); 

파일 2 :

:

$result = file_get_contents("http://localhost/file1.php"); 
$data = json_decode($result,true); 

$data->name // name is the array key 

는 그러나, 나는이 같은 오류를 얻고있다

개체가 아닌 개체의 속성을 가져 오려고합니다.

+0

변수의 어떤 종류가있다'$의 data'? 그것을 덤프 해 보라.'var_dump ($ data)' –

+0

@Jorge 나는 그것을 시도했다. 결과를 null로 가져 오기. – user1059869

+0

'print_r ($ data)'어쩌면? –

답변

3

json_decode의 두 번째 매개 변수를 true로 전달하여 배열을 반환합니다.

사용이 :

$result = file_get_contents("http://localhost/file1.php"); 
$data = json_decode($result,true); 
echo $data['name']; 
+0

그것은 나를 위해 작동하지 않았다. – user1059869

+1

- 그렇지 않으면 원래 배열에'name' 키가 없다 (또는 스크립트가 올바른 JSON을 가져 오지 않음) – nickb